The as Operator


A runtime cast may be attempted without giving rise to an exception using the as operator. The syntax of the operator is:

expression as type

where expression is being cast to type. If the cast succeeds, a reference to type is returned. If the cast fails, a null reference is returned.

The following code uses the is operator to prevent an invalid cast from occurring.

// Runtime2 - The is operator preventing an invalid cast

using System;

class X { }
class Y : X { }

class Program
{
    static void Main()
    {
        X x = new X();
        
        Y y = x is Y ? (Y)x : null;

        if (y == null)
            Console.WriteLine("Cast y = (Y)x is not allowed");
        else
            Console.WriteLine("Cast y = (Y)x is allowed");
    }
}

The output of the program is as follows.

Cast y = (Y)x is not allowed

The statement

 Y y = x is Y ? (Y)x : null;

can more conveniently be replaced with an as operator as shown in the program below.

// Runtime3 - The as operator

using System;

class X { }
class Y : X { }

class Program
{
    static void Main()
    {
        X x = new X();

        Y y = x as Y;

        if (y == null)
            Console.WriteLine("Cast y = (Y)x is not allowed");
        else
            Console.WriteLine("Cast y = (Y)x is allowed");
    }
}

Again, the output of the program is as follows.

Cast y = (Y)x is not allowed