3.15. Casting with the as Operator
Problem
Ordinarily,
when you attempt a casting operation, the
.NET Common Language Runtime generates an
InvalidCastException
if the cast fails. Often, though, you
cannot guarantee in advance that a cast will succeed, but you also do
not want the overhead of handling an
InvalidCastException.
Solution
Use the as operator. The as
operator attempts the casting operation, but if the cast fails, the
expression returns a null instead of throwing an
exception. If the cast succeeds, the expression returns the converted
value. The following code shows how the as
operator is used:
public static void ConvertObj(Base baseObj)
{
Specific specificObj = baseObj as Specific;
if (specificObj == null)
{
// Cast failed
}
else
{
// Cast was successful
}
}where the Specific type derives from the
Base type:
public class Base {}
public class Specific : Base {}In this code fragment, the as operator is used to
attempt to cast the specificObj to the type
Base. The next lines contain an
if-else statement that tests the variable
baseObj to determine whether it is equal to
null. If it is equal to null,
you should prevent any use of this variable, since it might cause a
NullReferenceException
to be thrown.
Discussion
The as operator has the following syntax:
expressionastype
The expression and type are defined as follows:
-
expression A reference type.
-
type The type to which to cast the object defined by
expression.
This operation returns expression cast to the type defined by ...