Is Operator in C#


Is Operator in C#

 

The Is operator in C# is used to check if a type of an object is compatible with the other type. If type is not compatible, you will also see C# compiler will through an error in Visual Studio IDE.

 

Visual Studio 2010 IDE is smart enough to warn you when you try to use Is operator on types that are not compatible. If types are now compatible, you will see an warning message like following:


IsOpImg.jpg

 

 

The following syntax uses Is operator to check if item is a string type or not and return true if it is; otherwise returns false.

 

If (item is string)

 

The following syntax uses Is operator to check if a Car type is a Vehicle type or not and displays an appropriate message on the console.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace IsOperatorSample

{

    public class Animal

    {

    }

 

    public class Vehicle

    {

    }

 

    public class Car : Vehicle

    {

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            Vehicle v = new Vehicle();

            Animal a = new Animal();

            Car c = new Car();

 

            if (c is Vehicle)

            {

                Vehicle newV = (Vehicle)c;

                Console.WriteLine(c.ToString() + " is a Vehicle. ");

            }

            else

            {

                Console.WriteLine(c.ToString() + " is NOT a Vehicle. ");

            }

 

 

            if (c is Animal)

            {

                Console.WriteLine(c.ToString() + " is an Animal. ");

            }

            else

            {

                 Console.WriteLine(c.ToString() + " is NOT an Animal. ");

            }

      

            Console.ReadLine();

        }

    }

}

 

 

The output looks like following where you can see Car is a Vehicle while Car is not an Animal.


IsOpImg2.jpg

 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.