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>
).