C Basic Syntax: Example of using as operator

  • 2021-06-28 13:42:06
  • OfStack

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

The as operator only performs reference and boxed conversions.The as operator cannot perform other transformations, such as user-defined transforms, which should be performed using a cast expression.

expression as type

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

The as operator performs a conversion 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 < objArray.Length; ++i)
    {
      string s = objArray[i] as string;
      Console.Write("{0}:", i);
      if (s != null)
      {
        Console.WriteLine("'" + s + "'");
      }
      else
      {
        Console.WriteLine("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


Related articles: