[This is preliminary documentation and subject to change]
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
where:
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.
// 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 + "'" ); 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
C# Keywords | is | ?: | Operator Keywords