How to: Safely Cast by Using as and is Operators (C# Programming Guide)

Because objects are polymorphic, it is possible for a variable of a base class type to hold a derived type. To access the derived type's method, it is necessary to cast the value back to the derived type. However, to attempt a simple cast in these cases creates the risk of throwing an InvalidCastException. That is why C# provides the is and as operators. You can use these operators to test whether a cast will succeed without causing an exception to be thrown. In general, the as operator is more efficient because it actually returns the cast value if the cast can be made successfully. The is operator returns only a Boolean value. It can therefore be used when you just want to determine an object's type but do not have to actually cast it.


The following examples show how to use the is and as operators to cast from one reference type to another without the risk of throwing an exception. The example also shows how to use the as operator with nullable value types.

class SafeCasting
    class Animal
        public void Eat() { Console.WriteLine("Eating."); }
        public override string ToString()
            return "I am an animal.";
    class Mammal : Animal { }
    class Giraffe : Mammal { }

    class SuperNova { }

    static void Main()
        SafeCasting app = new SafeCasting();

        // Use the is operator to verify the type. 
        // before performing a cast.
        Giraffe g = new Giraffe();

        // Use the as operator and test for null 
        // before referencing the variable.

        // Use the as operator to test 
        // an incompatible type.
        SuperNova sn = new SuperNova();

        // Use the as operator with a value type. 
        // Note the implicit conversion to int? in  
        // the method body. 
        int i = 5;

        double d = 9.78654;

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");

    void UseIsOperator(Animal a)
        if (a is Mammal)
            Mammal m = (Mammal)a;

    void UseAsOperator(object o)
        Mammal m = o as Mammal;
        if (m != null)
            Console.WriteLine("{0} is not a Mammal", o.GetType().Name);

    void UseAsWithNullable(System.ValueType val)
        int? j = val as int?;
        if (j != null)
            Console.WriteLine("Could not convert " + val.ToString());

See Also


Types (C# Programming Guide)

Casting and Type Conversions (C# Programming Guide)

Nullable Types (C# Programming Guide)

Change History




July 2008

Added topic.

Content bug fix.