Analysis of the use of is and as keywords in type conversion, analysis of

Source: Internet
Author: User

Analysis of the use of is and as keywords in type conversion, analysis of

Is checks whether the object is compatible with the specified type and returns a Boolean value of true or false. It is worth noting that when using is for type conversion, an exception will never be thrown. For example:

Object o = new Object ();

Boolean a = (o is object); // returns a = true

Boolean B = (o is Employee) // return B = false

If the object is null, the returned result is false because no object of its type can be checked and null is not an object.

Common usage of the is OPERATOR:

If (o is Employee ){

Employee e = (Employee) o; // type conversion

}

In the above Code, the o object is checked for two types. The is operator first checks whether o is compatible with the Employee type. if yes, during internal conversion of the if statement, CLR (when the common language is running) checks again whether o references an Employee. CLR type checks enhance security, but undoubtedly cause some performance loss,

Therefore, C # provides the AS operator to simplify the code writing and improve performance.

Employee e = o as Employee;

If (e! = Null ){

// Use e

}

In this Code, CLR checks whether o is compatible with the Employee type. If yes, as returns a non-null reference to the same object. If it is not compatible with the Employee type, as returns null, so that CLR only verifies the object type once, which is much faster than is.

The as operator works in the same way as forced type conversion, but it never throws an exception. If the object cannot be converted, null is returned, therefore, before using the as conversion type, you must determine whether the object is null. Otherwise, an exception occurs, such:

Object o = new Object ();

Employee e = o as Employee; // type conversion failed here, e = null; no exception is thrown

E. Tostring (); // use e to throw NullReferenceException

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.