Sunday, December 19, 2010

Explicit Casting vs. Using the "as" Keyword

There are (at least) two ways to cast an object in C# and I recently became curious about the difference. Apparently, if an explicit cast fails it will throw an InvalidCastException. Alternatively, if a cast that uses the "as" keyword fails, the target object will be given a null value.

So using the "as" keyword is perhaps slightly riskier since the program will continue on its merry way when there's a failed cast until you try to use your object and find out that it's null. However, I suspect most of the time this won't matter because the object is likely being casted for immediate use. So if for some reason you want your casts to be able to produce a null value upon failure, the "as" keyword is the way to go. Other than that, it seems like the difference will not have severe implications.

No comments:

Post a Comment