3.10. 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 over-head of handling an InvalidCastException.
Solution
Use the as operator. The as operator attempts the conversion operation, but if the conversion fails, the expression returns a null instead of throwing an exception. If the conversion succeeds, the expression returns the converted value. The code that follows shows how the as operator is used:
public static void ConvertObj(Specific specificObj)
{
Base baseObj = specificObj as Base;
if (baseObj == 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 convert 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:
expression as type |
The expression and type are defined as follows:
expressionAn expression.
typeThe type to which to convert the object represented by
expression.
This operation returns expression converted to ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access