Header Ads Widget

C sharp(#) as Keyword and its use

The as keword explicitly converts the result of an expression to a given reference or nullable value type. If the conversion isn't possible, the as keyword returns null. Unlike a cast expression, the as operator never throws an exception.

The as keyword used to perform conversions between compatible types. It has a very similar role to the is operator, however, it works differently under the hood.

expression as type


        using System;
        class ItsEdupoint1 { }
        class ItsEdupoint2 { }
		class Lotus {
                  static void Main()

                      // creating and initializing object array
                      object[] obj = new object[5];
                      obj[0] = new ItsEdupoint2();
                      obj[1] = new ItsEdupoint2();
                      obj[2] = "Dot Net";
                      obj[3] = 123.5;
                      obj[4] = null;

                      for (int j = 0; j <s; obj.Length; ++j) {

                          string str = obj[j] as string;
                          Console.Write("{0}:", j);         
                          if (str != null) {
                              Console.WriteLine("'" + str + "'");
                          else {
                              Console.WriteLine("Is is not a string");


Post a Comment