Friday, April 11, 2008

Casting with "as" in C#

C# provides a couple of methods for casting. One way is the way most familiar to C/C++/Java programmers:


Foo foo = (Foo)bar;


The second way is through the use of the "as" keyword, which may feel more comfortable to ex-VB programmers (since it also has an "as" keyword):


IFoo foo = someObject as IFoo;


...and the great advantage of the latter form is that "as" returns null if the object does not support the type (or interface) in question, instead of throwing an exception. This is really handy if you're trying to do invoke a method at runtime and you want to only do it to the object if it supports the interface:


if (foo != null)
{
foo.DoSomethingInterestingNow();
}


I guess you could also do this with "is" and a cast too:


if (bar is IFoo)
{
foo = (IFoo)bar;
// or:
//foo = bar as IFoo;
foo.DoSomethingInterestingNow();
}

No comments: