As in C #

Source: Internet
Author: User

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 #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.