as
Visual Studio .NET 2003
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:
- expression
- An expression of a reference type.
- type
- A reference type.
Remarks
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.
Example
// 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 + "'" );
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
See Also
C# Keywords | is | ?: | Operator Keywords