as (C# Reference)
The as operator is used to perform certain types of conversions between compatible reference types. For example:
class csrefKeywordsOperators
{
class Base
{
public override string ToString()
{
return "Base";
}
}
class Derived : Base
{ }
class Program
{
static void Main()
{
Derived d = new Derived();
Base b = d as Base;
if (b != null)
{
Console.WriteLine(b.ToString());
}
}
}
}
Remarks
The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception. Consider the following expression:
expression as type
It is equivalent to the following expression except that expression is evaluated only one time.
expression is type ? (type)expression : (type)null
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 by using cast expressions.
Example
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
*/
C# Language Specification
For more information, see the following sections in the C# Language Specification:
6 Conversions
7.9.11 The as operator
See Also
Concepts
Reference
Operator Keywords (C# Reference)