C# “is” and “as” operators


The is operator checks whether an object is compatible with a given type, and the result of the evaluation is a Boolean: true or false. The is operator will never throw an exception. The following code demonstrates:

 

Object o = new Object();

            Boolean b1 = (o is Object); // b1 is true.

            Boolean b2 = (o is Employee); // b2 is false.

 

If the object reference is null, the is operator always returns false because there is no objectavailable to check its type. The is operator is typically used as follows:

 

if (o is Employee)

            {

                Employee e = (Employee)o;

                // Do something.

            }

 

In this code, the CLR is actually checking the object’s type twice: The is operator first checks to see if o is compatible with the Employee type. If it is, inside the if statement, the CLR again verifies that o refers to an Employee when performing the cast. The CLR’s type checking improves security, but it certainly comes at a performance cost, because the CLR must determine the actual type of the object referred to by the variable (o), and then the CLR must walk the inheritance hierarchy, checking each base type against the specified type (Employee).

 

C# offers a way to simplify this code and improve its performance by providing an as operator:

 

Employee e = o as Employee;

            if (e != null)

            {

                // Use e within the ‘if’ statement.

            }

In this code, the CLR checks if o is compatible with the Employee type, and if it is, as returnsa non-null reference to the same object. If o is not compatible with the Employee type, the as operator returns null. Notice that the as operator causes the CLR to verify an object’s type just once. The if statement simply checks whether e is null; this check can be performed faster than verifying an object’s type.

 

The as operator works just as casting does except that the as operator will never throw an exception. Instead, if the object can’t be cast, the result is null. You’ll want to check to see whether the resulting reference is null, or attempting to use the resulting reference will cause a System.NullReferenceException to be thrown. The following code demonstrates:

   Object o = new Object(); // Creates a new Object object

            Employee e = o as Employee; // Casts o to an Employee

            // The cast above fails: no exception is thrown, but e is set to null.

            e.ToString(); // Accessing e throws a NullReferenceException.

To simplify the understanding using the “as” operator  increases the performance compared to “is” as demonstrated above as CLR checks the type only once in the former case.

 

This entry was posted in C#. Bookmark the permalink.

Leave a comment