What is the purpose of ‘is’ operator in C#?

CsharpProgrammingServer Side Programming

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();
   }
}
raja
Published on 17-Sep-2018 13:05:05
Advertisements