Saturday, September 22, 2007

As Keyword in C#

The "as" keyword in C# attempts to cast an instance to a specific type and if it fails returns null.

What is the different between explicitly cast ?

string str = (string) Request["nullSession"];
string str = Request["nullSession"] as string;

Both of them return the same (NULL)...

However probably, I will stick with my casting style because
1. It confused me when I need to convert from C# to VB
2. I can not using as keyword to replace
(int) 123.23
where I expect to get 123 as integer

----
123.21 as int

//throws The as operator must be used with a reference type ('int' is a value type)

123.21 as int16
//throws The as operator must be used with a reference type ('short' is a value type)

123.21 as double
//throws The as operator must be used with a reference type ('double' is a value type)


No comments: