C# "as" cast vs classic cast
With the "classic" method, if the cast fails, an InvalidCastException
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.
Note:
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.
Null comparison is MUCH faster than throwing and catching exception. Exceptions have significant overhead - stack trace must be assembled etc.
Exceptions should represent an unexpected state, which often doesn't represent the situation (which is when as
works better).
In some cases, it's easily to deal with a null
than an exception. In particular, the coalescing operator is handy:
SomeClass someObject = (obj as SomeClass) ?? new SomeClass();
It also simplifies code where you are (not using polymorphism, and) branching based on the type of an object:
ClassA a;
ClassB b;
if ((a = obj as ClassA) != null)
{
// use a
}
else if ((b = obj as ClassB) != null)
{
// use b
}
As specified on the MSDN page, the as
operator is equivalent to:
expression is type ? (type)expression : (type)null
which avoids the exception completely in favour of a faster type test, but also limits its use to types that support null
(reference types and Nullable<T>
).