C # as is type conversion

Source: Internet
Author: User

There are two operators "is" and "as" to judge and convert types. The specific differences and usage are as follows:
Is in the judgment of the type. Returns true and false. If an object is of a certain type or its parent type, true is returned; otherwise, false is returned. In addition, the is operator will never throw an exception. The Code is as follows:

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 code below
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. This programming paradigm is very common. c # provides a new type check and conversion method. That is, the as operator can improve the 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 the performance even if it is equivalent to the above Code and performs only one type check at the same time. 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.