Friday, May 16, 2008

[C#] More about Typecasting with 'as' and 'is'

Taken from this CodeGuru article I found by Jay Miller

Often in my programming experiences with C# I want to check if an object is a specific type without throwing a code stopping exception. So I end up writing something very similar to this:

if (myObject.GetType().ToString().Name == "Canvas")
{
// Wicked code goes here.
}

or

Canvas myCanvas = myObject as Canvas; // If invalid typecast this will return null.
if (myCanvas != null)
{
// Wicked code goes here.
}

I've found a slightly cleaner way to accomplish this:

Canvas myCanvas = myObject as Canvas;
if (myCanvas is Canvas)
{
// Wicked code goes here.
}

The change is subtle, but I think that it makes this comparison much more clear and easy to read. Also, according to the referenced article, this comparison via 'is' is slightly more efficient then comparing against null.

No comments: