The is Operator

Whether an object is of a given type can be determined using the is operator. The syntax of the is operator is:

expression is type

where expression is an expression whose type is being tested against type. When the type of expression is the same as or compatible with type, the outcome of the operation is true. Hence if the outcome is true, expression can be cast to type.

Below is a simple example that makes use of the is operator.

// Runtime1 - The is operator

using System;

class X { }
class Y : X { }

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

        if (x is X) Console.WriteLine("x is X");
        if (y is X) Console.WriteLine("y is X because Y derives from X");

        if (x is Y) Console.WriteLine("Doesn't Display = x not a Y");

        if (x is object) Console.WriteLine("x is an object");

The output of the program is shown below.

x is X
y is X because Y derives from X
x is an object