As: Used to check for certain types of conversions between compatible reference types.
Employee Myemployee = MyObject as Employee;
if (myemployee! = null)
{ }
In this code, the CLR verifies that MyObject is compatible with the employee type, and if so, as returns a non-null reference to the same object. If the MyObject is incompatible with the employee type, the AS operator returns NULL.
Note: The as operator causes the CLR to verify the type of the object only once. The IF statement simply checks if Myemployee is null. This check is much faster than verifying the type of the object.
The as operator works the same way as coercion type conversions, except that it never throws an exception. Conversely, if the object cannot be converted, the result is null. So, it's a good idea to check if the final generated reference is null. If you attempt to use the final generated reference directly, a System.NullReferenceException exception is thrown. This is demonstrated in the following code:
Object o = new Object (); Create a new Object object.
Employee E = o as Employee; Transform O into an employee
E.tostring (); Access E throws a NullReferenceException exception
Note:
The as operator is similar to the cast operation. But cannot be converted, the as returns null rather than throws an exception.
Example:
expression as type it is equivalent to the following expression, but only once expression is evaluated.
Expression is Type? (type) expression: (type) NULL
Note: The as operator only performs reference conversions and boxing conversions. The as operator cannot perform other transformations, which should be performed using a cast expression if the user-defined conversion.
Source Address: http://www.xici.net/d155333263.htm
As (go) in C #