as Operator

You can use the as operator in C# to convert a class into another class within the same inheritance hierarchy. The as operator is equivalent to using casting with some minor differences as will be explained later. The following shows the syntax of using the asoperator.

myObject as DestinationType;

The left operand is the object that will be converted and the right operand is the destination type for which that object will be converted to. The following codes are equivalent.

Destination someObject = (Destination)myObject;
Destination someObject = myObject as Destination;

The first code where you used casting will cause an exception if the conversion fails—that is if the conversion is not possible for the two classes. The second code where you used the as operator will return null if the conversion has failed. You could also use the as operator when calling a method of a derived class through its base class. Refer to the classes from the last lesson.

(myAnimal as Dog).Run();

The above code will throw a NullReferenceException if the myAnimal object cannot be converted to a Dog instance.