1.

Role of “as” operator in C#

Answer»

The “as” operator in C# is SOMEWHAT similar to the “is” operator. HOWEVER, the “is” operator returns boolean values but the “as” operator returns the object types if they are compatible to the given type, otherwise it returns null.

In other words, it can be SAID that conversions between compatible types are PERFORMED using the “as” operator.

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

namespace IsAndAsOperators {    CLASS A    {        public int a;    }    class B    {        public int x;        public double y;    }    class Program    {        static void Main(string[] args)        {            A obj1 = new A();            obj1.a = 9;            B obj2 = new B();            obj2.x = 7;            obj2.y = 3.5;            System.Console.WriteLine("The object obj1 is of class A? : {0}", func(obj1));            System.Console.WriteLine("The object obj2 is of class A? : {0}", func(obj2));        }        public static string func(dynamic obj)        {            A tempobj = obj as A;            if (tempobj != null)                return "This is an object of class A with value " + tempobj.a;                return "This is not an object of class A";                 }    } }

The output of the above program is given as follows:

The object obj1 is of class A? : This is an object of class A with value 9 The object obj2 is of class A? : This is not an object of class A


Discussion

No Comment Found