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:

1<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.

1class ClassA { }
2class ClassB { }
3 
4class MainClass
5{
6    static void Main()
7    {
8        object[] objArray = new object[6];
9        objArray[0] = new ClassA();
10        objArray[1] = new ClassB();
11        objArray[2] = "hello";
12        objArray[3] = 123;
13        objArray[4] = 123.4;
14        objArray[5] = null;
15 
16        for (int i = 0; i < objArray.Length; ++i)
17        {
18            string s = objArray[i] as string;
19            Console.Write("{0}:", i);
20            if (s != null)
21            {
22                Console.WriteLine("'" + s + "'");
23            }
24            else
25            {
26                Console.WriteLine("not a string");
27            }
28        }
29    }
30}
31/*
32Output:
330:not a string
341:not a string
352:'hello'
363:not a string
374:not a string
385:not a string
39*/