Differences between the is and as operators in C #

Source: Internet
Author: User

1. concept description

Is the operator used in C # To determine type compatibility. Check whether an object is compatible with other specified types. If an object is of a certain type or its parent type, true is returned, otherwise, false is returned.

Is rules are as follows:

Check the compatibility of object types and return results, true or false;
No exception is thrown;
If the object is null, the return value is always false.

Example
System. Boolean b1 = (o is System. Object); // b1 is true
System. Boolean b2 = (o is Employee); // b2 is false
If the object reference is null, the is Operator always returns false because no object can check its type, just like the following code.
If (o is Employee)

{
Employee e = (Employee) o;
// Use e in the if statement
}
In the code above, CLR checks the object type twice: The is operation first checks whether the object referenced by o is compatible with the employee type.

If it is compatible, the CLR in the if statement checks whether o is referenced by an Employee when executing the conversion.

As is the operator used in C # for determining type compatibility and type conversion. It also performs type judgment and type conversion. It can simplify the Code while improving the performance.

The as rules are as follows:

Check the compatibility of object types and perform forced conversion. Return results. If not, return null;
No exception is thrown;
If the result is null, The NullReferenceException is thrown when the type conversion is forced.
Employee e = o as Employee;
If (e! = Null)
{
// Use e in the if statement
}
This as operation only performs one type check, which improves the performance. If the types are the same, a non-null reference is returned. Otherwise, an empty reference is returned.

Related Article

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.