is Operator

The is operator in C# allows you to test if an object can be converted into another object mainly by using casting. The is operator requires two operands, the one that will be tested, and the type to which that object will be compared. The is operator returns a boolean value. For example, supposed we have a class named Animal, then we created an instance of it:

using System;
 
namespace IsOperatorDemo
{
    class Animal
    {
 
    }
 
    class Program
    {
        public static void Main()
        {
            Animal myAnimal = new Animal();
 
            if (myAnimal is Animal)
            {
                Console.WriteLine("myAnimal is an Animal!");
            }
        }
    }
}

Example 1 – Using the is Operator

myAnimal is an Animal

You see the is operator in action. We use it as the condition for our if statement. It checked if the myAnimal object is an instance of an Animal. Since that was true, the code inside the if statement executed.

The is operator can also check if a particular object is in the inheritance hierarchy of a particular type. Consider the next example:

using System;
 
namespace IsOperatorDemo2
{
    class Animal
    {
 
    }
 
    class Dog : Animal
    {
 
    }
 
    class Program
    {
        public static void Main()
        {
            Dog myDog = new Dog();
 
            if (myDog is Animal)
            {
                Console.WriteLine("myDog is an Animal!");
            }
        }
    }
}

Example 2 – Is Operator Also Checks for Inheritance

myDog is an Animal!

So we created another class named Dog which is a derived class of Animal. We created a new Dog instance and then test if it is an Animal or a derived class of Animal using the is operator. Since the Dog inherits Animal, expression results to true. If you will transform this in a sentence: “My Dog is an Animal”. What will happen if we reverse it?

Animal myAnimal = new Animal();

if (myAnimal is Dog /* Error */)
{
    Console.WriteLine("myAnimal is a Dog!");
}

This will not produce an error. The expression will only result to false. This  makes sense since not all animals are dogs, but all dogs are animals.

An alternative way to check for the type of an object is by using the typeof operator and the GetType() method of the System.Objectclass.

if (myAnimal.GetType() == typeof(Animal))
{
}

The GetType() method returns a System.Type object which indicates the type of the object that called it. The typeof operator accepts the name of a type and returns its corresponding System.Type object as well.