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


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!

Updated on: 23-Jun-2020

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements