Friday, August 29, 2008

[.NET] Difference between casting and 'as' operator in C#

This is an easy one - but it can be useful to someone so here it comes:

The 'as' operator in C# is a tentative cast - if it's impossible to cast (types are not compatible) instead of throwing an exception as the direct cast the 'as' operator sets the reference to null.

So you can have something like:

MyClass myObj = new MyClass();
MyOtherClass myOtherObj = myObj as MyOtherClass;
if (obj != null)
//cast was successful
//a little bit of a fuck-up

The correspondent in VB is the TryCast (usage is the same as DirectCast but it doesn't throw any exception).

No comments: