The 'is' operator in C#

Date Added: June 04, 2010 06:51 by By Edward
Categories: ASP.NET, Other

The 'is' operator is used to check whether the run-time type of an object is compatible with a given type, and is a "reference type". This is very handy when you have code somewhere in a business or data layer and you cannot figure out why an exception is occuring.

For example:

 

public static void RunThis()
    {
        // For this example the following obj is a class already created              
        object obj = new MyClass();
        CastCheck(obj);
    }

    public static void CastCheck(object obj)
    {
        // For this example the following classes are already created  
        Class1 a;
        Class2 b;
        if (obj is Class1)
        {
            Console.WriteLine("obj is Class1");
            a = (Class1)obj; // do something with a              
        }
        else if (obj is Class2)
        {
            Console.WriteLine("v is Class2");
            b = (Class2)obj; // do something with b              
        }
        else
        {
            Console.WriteLine("obj is neither Class1 nor Class2.");
        }
    }

 

The 'is' operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered by the is operator.

 

Comments are closed

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net