Breaking News

Friday, September 24, 2010

.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.

Example:

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

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;
if(s!=null)
{
 DoSomething();
}

Happy programming!

No comments:

Post a Comment

Designed By Published.. Blogger Templates