C# as Operator


You can use the as operator to perform certain types of conversions between compatible reference types or nullable types. The as operator is like a cast operation. However, if the conversion isn’t possible, as returns null instead of raising an exception. Note that the as operator 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 as operator is, in general, preferable to casting when using reference types.

The as operator converts a type into a specified reference type, using the following syntax:

<operand> as <type>

This is possible only in certain circumstances:

  • If is of type
  • If can be implicitly converted to type
  • If can be boxed into type

If no conversion from to is possible, then the result of the expression will be null.

Here is an example from MSDN at Microsoft.

class ClassA { }
class ClassB { }

class MainClass
{
    static void Main()
    {
        object[] objArray = new object[6];
        objArray[0] = new ClassA();
        objArray[1] = new ClassB();
        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");
            }
        }
    }
}
/*
Output:
0:not a string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string
*/