1.

How to use ‘is’ operator in C#?

Answer»

The ‘is’ operator in C# is used to check if the given object is compatible with the given TYPE DYNAMICALLY. This operator returns true if the object is compatible with the type and false otherwise i.e. it returns boolean VALUES. If there are null objects, then ‘is’ operator returns false.

A PROGRAM that demonstrates the ‘is’ operator in C# is given as follows:

namespace Demo {    class A    {        public int a;    }    class B    {        public int b;    }    class Program    {        public static void Main(string[] args)        {            A obj1 = NEW A();            obj1.a = 5;            B obj2 = new B();            obj2.b = 9;            bool flag1 = (obj1 is A);            System.Console.WriteLine("The object obj1 is of class A ? " + flag1.ToString());            bool flag2 = (obj2 is A);            System.Console.WriteLine("The object obj2 is of class A ? " + flag2.ToString());        }    } }

The output of the above program is given as follows:

The object obj1 is of class A ? True The object obj2 is of class A ? False


Discussion

No Comment Found