The difference between C # is and as

Source: Internet
Author: User

The judgment and conversion of the type are the 2 operators of IS and as. Specific differences and usage are as follows
IS is the judgment of the type. Returns True and false. Returns True if an object is of a type or its parent type, otherwise it returns false. In addition, the IS operator never throws an exception. The code is as follows:

System.Boolean B1 = (O is System.Object);//b1 true
System.Boolean B2 = (O is Employee);//b2 False if the object reference is null, the IS operator always returns false because no object can check its type, just like the code below
If (O is Employee) {
Employee E = (employee) O;
Use e in the IF statement
in the above code, the CLR actually checks the object type two times: The is operation first checks whether the object referenced by O is compatible with the employee type. If compatible, the CLR checks whether O is an employee reference in the IF statement when it performs the conversion. This programming paradigm is very common, and C # provides a new type-checking, conversion method. As operator, he can improve performance while simplifying the code. The code is as follows:
Employee E = o as Employee;
if (E! = null)
{
Use e in the IF statement
This as operation improves performance even if it is equivalent to the above code, and only 1 types are checked. Returns a non-null reference if the type is the same, or returns a null reference.

The difference between C # is and as

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.