The c# as operator is used to convert between compatible reference or nullable types. It is similar to a cast operation, except that it will set the result of the conversion to null for a failed conversion, rather than throwing an exception.
The following is an excerpt from the official C# 4.0 specification:
7.10.11 The as operator The as operator is used to explicitly convert a value to a given reference type or nullable type. Unlike a cast expression (§7.7.6), the as operator never throws an exception. Instead, if the indicated conversion is not possible, the resulting value is null.
In an operation of the form E as T, E must be an expression and T must be a reference type, a type parameter known to be a reference type, or a nullable type. Furthermore, at least one of the following must be true, or otherwise a compile-time error occurs:
An identity (§6.1.1), implicit nullable (§6.1.4), implicit reference (§6.1.6), boxing (§6.1.7), explicit nullable (§6.2.3), explicit reference (§6.2.4), or unboxing (§6.2.5) conversion exists from E to T.
The type of E or T is an open type.
E is the null literal.
If the compile-time type of E is not dynamic, the operation E as T produces the same result as
E is T ? (T)(E) : (T)null
except that E is only evaluated once. The compiler can be expected to optimize E as T to perform at most one dynamic type check as opposed to the two dynamic type checks implied by the expansion above.
If the compile-time type of E is dynamic, unlike the cast operator the as operator is not dynamically bound (§7.2.2). Therefore the expansion in this case is:
E is T ? (T)(object)(E) : (T)null
Note that some conversions, such as user defined conversions, are not possible with the as operator and should instead be performed using cast expressions.
In the example
class X
{
public string F(object o) {
return o as string; // OK, string is a reference type
}
public T G<T>(object o) where T: Attribute {
return o as T; // Ok, T has a class constraint
}
public U H<U>(object o) {
return o as U; // Error, U is unconstrained
}
}
the type parameter T of G is known to be a reference type, because it has the class constraint. The type parameter U of H is not however; hence the use of the as operator in H is disallowed.