SoFunction
Updated on 2025-03-06

Basic C# syntax: Example of the as operator

The as operator is similar to a cast operation. However, if the conversion cannot be performed, as returns null instead of throwing an exception.

The as operator only performs reference and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should be performed using cast expressions.

expression as type

Equivalent to (but only counted once)
expression is type ? (type)expression : (type)null

The as operator is used to perform conversions between compatible reference types. For example:

// cs_keyword_as.cs
// The as operator.
using System;
class Class1
{
}

class Class2
{
}

class MainClass
{
  static void Main()
  {
    object[] objArray = new object[6];
    objArray[0] = new Class1();
    objArray[1] = new Class2();
    objArray[2] = "hello";
    objArray[3] = 123;
    objArray[4] = 123.4;
    objArray[5] = null;

    for (int i = 0; i < ; ++i)
    {
      string s = objArray[i] as string;
      ("{0}:", i);
      if (s != null)
      {
        ("'" + s + "'");
      }
      else
      {
        ("not a string");
      }
    }
  }
}
//=============================================================// 
0:not a string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string