What is the purpose of ‘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

type is the name of the type

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

Example

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();
   }
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 23-Jun-2020

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements