Chris Chris - 1 year ago 85
C# Question

C# "as" cast vs classic cast

Possible Duplicate:

Casting vs using the ‘as’ keyword in the CLR

I recently learned about a different way to cast. Rather than using

SomeClass someObject = (SomeClass) obj;

one can use this syntax:

SomeClass someObject = obj as SomeClass;

which seems to return null if obj isn't a SomeClass, rather than throwing a class cast exception.

I see that this can lead to a NullReferenceException if the cast failed and I try to access the someObject variable. So I'm wondering what's the rationale behind this method? Why should one use this way of casting rather than the (old) one - it only seems to move the problem of a failed cast "deeper" into the code.

Answer Source

With the "classic" method, if the cast fails, an exception is thrown. With the as method, it results in null, which can be checked for, and avoid an exception being thrown.

Also, you can only use "as" with reference types, so if you are typecasting to a value type, you must still use the "classic" method.


The as method can only be used for types that can be assigned a null value. That use to only mean reference types, but when .NET 2.0 came out, it introduced the concept of a nullable value type. Since these types can be assigned a null value, they are valid to use with the as operator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download