How to use ‘is’ operator in C#?



The "is" operator in C# checks whether the run-time type of an object is compatible with a given type or not.

The following is the syntax −

expr is type

Here, expr is the expression and type is the name of the type

The following is an example showing the usage of is operator in C# −

Example

 Live Demo

using System;
class One { }
class Two { }

public class Demo {
   public static void Test(object obj) {
      One x;
      Two y;
      if (obj is One) {
         Console.WriteLine("Class One");
         x = (One)obj;
      } else if (obj is Two) {
         Console.WriteLine("Class Two");
         y = (Two)obj;
      } else {
         Console.WriteLine("None of the classes!");
      }
   }

   public static void Main() {
      One o1 = new One();
      Two t1 = new Two();
      Test(o1);
      Test(t1);
      Test("str");
      Console.ReadKey();
   }
}

Output

Class One
Class Two
None of the classes!
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements