Export (0) Print
Expand All
59 out of 72 rated this helpful - Rate this topic


The as operator is used to perform conversions between compatible types. The as operator is used in an expression of the form:

expression as type


An expression of a reference type.
A reference type.


The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an expression of the form:

expression as type

is equivalent to:

expression is type ? (type)expression : (type)null

except that expression is evaluated only once.

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


// cs_keyword_as.cs
// The as operator
using System;
class MyClass1 

class MyClass2 

public class IsTest 
   public static void Main() 
      object [] myObjects = new object[6];
      myObjects[0] = new MyClass1();
      myObjects[1] = new MyClass2();
      myObjects[2] = "hello";
      myObjects[3] = 123;
      myObjects[4] = 123.4;
      myObjects[5] = null;

      for (int i=0; i<myObjects.Length; ++i) 
         string s = myObjects[i] as string;
         Console.Write ("{0}:", i);
         if (s != null)
            Console.WriteLine ( "'" + s + "'" );
            Console.WriteLine ( "not a string" );


0:not a string
1:not a string
3:not a string
4:not a string
5:not a string

See Also

C# Keywords | is | ?: | Operator Keywords

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
© 2014 Microsoft. All rights reserved.