Feature Post


.NET: is vs as

Small difference between is and as

From MSDN: is keyword
The is operator is used to check whether the run-time type of an object is compatible with a given type

From MSDN: as keyword
The as operator is used to perform conversions between compatible types.


object s = "this is a test";
string str=string.Empty;
if( s is string)
{    str = s as string;

Note that, the example above is an anti-pattern. It's expensive to do is then as. Why? because it unboxes 's' object twice. For reference types, you should just do as, then check for null to see if it worked.

Like following:

string str = s as string;

Happy programming!

No comments