DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 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:

expression as type

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 type if the cast succeeds. If the cast fails, a null is returned, and an InvalidCastException is not thrown. Because of this, you should always check the result for null.

This operator does not work with user-defined conversions (both explicit and implicit). A user-defined conversion method extends one type to allow it to be converted to another type. This is done by adding a method, such as the following, to a class or structure:

public struct MyPoint
{
    public static explicit operator MyPoint(System.Drawing.Point pt) 
    {
        // Convert a Point structure to a MyPoint structure type
        return (new MyPoint( ));
    }
}

This method allows a System.Drawing.Point structure to be cast to an object of type MyPoint. Due to the use of the explicit keyword, the cast must be explicitly defined:

System.Drawing.Point systemPt = new System.Drawing.Point(0, 0);
MyPoint pt = (MyPoint)systemPt;

If you attempt to use the as operator in a user-defined conversion, the following compiler error is shown:

Cannot convert type 'Chapter_Code.Vector32' to 'string' via a built-in conversion

This type of conversion does not work with unboxing conversions, either. An unboxing conversion converts a previously boxed value type to its original value type, such as with the following code:

int x = 5;
object obj = x;         // Box x
int originalX = obj as int;   // Attempt to unbox obj into an integer

If you attempt to use the as operator in an unboxing conversion, the following compiler error is shown:

The as operator must be used with a reference type ('int' is a value type)

because as indicates that the cast cannot be performed by returning null, but there is no such thing as a null value for an int.

See Also

See Recipe 3.14 and Recipe 3.16; see the "( ) Operator," "as Operator," and "is Operator" topics in the MSDN documentation.

    [ Team LiB ] Previous Section Next Section