I'm CaLendarW Blog

C# as operator

by calendarw on Aug.04, 2009, under coding snippet

as operator 係用黎做 casting 的

static void Main()
{
    double x = 1234.7;
    int a;
    // Cast double to int.
    a = (int)x;
    System.Console.WriteLine(a);
}
// Output: 1234

如果用 boxing 黎轉 type 既話, 錯 type 的話就會 throw InvalidCastException, 但如果用 as operator 就唔會 throw InvalidCastException, 而 value 就會係 null

public static void Main()
{
    object time1 = DateTime.Now;
    DateTime? t = time1 as DateTime?;    // valid casting
    int? wrongCast = time1 as int?;    // wrongCast == null
}
:

Leave a Reply

You must be logged in to post a comment.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!