The as keyword is an operator similar to a cast. If a cast is not possible, using as produces null rather than resulting in an InvalidCastException.
expression as type is equivalent to expression is type ? (type)expression : (type)null with the caveat that as is only valid on reference conversions, nullable conversions, and boxing conversions. User-defined conversions are not supported; a regular cast must be used instead.
For the expansion above, the compiler evaluates expression only once and performs a single runtime type check, unlike the two checks in that sample.
as is useful when a value might be one of several reference types. A successful as does one type check. Testing with is and then casting does two. It does not perform user-defined conversions, and it cannot unbox to a non-nullable value type.
If an argument is expected to be an instance of a specific type, a regular cast is preferred because its purpose is clearer to the reader.
Because a call to as may produce null, always check the result to avoid a NullReferenceException.
Example usage
object something = "Hello";
Console.WriteLine(something as string); //Hello
Console.WriteLine(something as Nullable<int>); //null
Console.WriteLine(something as int?); //null
//This does NOT compile:
//destination type must be a reference type (or a nullable value type)
Console.WriteLine(something as int);
Equivalent example without using as:
Console.WriteLine(something is string ? (string)something : (string)null);
This is useful when overriding the Equals function in custom classes.
class MyCustomClass
{
public override bool Equals(object obj)
{
MyCustomClass customObject = obj as MyCustomClass;
// if it is null it may be really null
// or it may be of a different type
if (Object.ReferenceEquals(null, customObject))
{
// If it is null then it is not equal to this instance.
return false;
}
// Other equality controls specific to class
}
}