How to use ‘as’ operator in C#?

CsharpProgrammingServer Side Programming

The "as" operator perform conversions between compatible types. It is like a cast operation and it performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

The following is an example showing the usage of as operation in C#. Here ‘as’ is used for conversion:

string s = obj[i] as string;

Try to run the following code to work with ‘as’ operator in C# −

Example

 Live Demo

using System;

public class Demo {
   public static void Main() {
      object[] obj = new object[2];
      obj[0] = "jack";
      obj[1] = 32;

      for (int i = 0; i < obj.Length; ++i) {
         string s = obj[i] as string;
         Console.Write("{0}: ", i);
         if (s != null)
         Console.WriteLine("'" + s + "'");
         else
         Console.WriteLine("This is not a string!");
      }
      Console.ReadKey();
   }
}

Output

0: 'jack'
1: This is not a string!
raja
Published on 03-Aug-2018 17:01:13
Advertisements