Use of the C # operator as and is

Source: Internet
Author: User

The as operator is similar to a type conversion, but when the conversion fails, the AS operator produces null instead of throwing an exception. In form, the expression of this type:

Expression_r as type

The as operator only performs reference conversions and boxing conversions.

The as operator cannot perform other transformations, such as user-defined conversions, which should use case expressions instead of their execution.

It's pretty much the same, but it's not going to help you with any conversions. Therefore, you need to display the conversion from the.

Is operator, which automatically checks whether the current situation is compatible with the type and returns the result. And it doesn't throw an exception. If the object reference is null, the is always returns false.

is example:

if (CLS1 is Class2) 
    Class2 cls2 = (Class2) cls1;
else
    System.Console.WriteLine ("Error 2!");

As Example:

Class2 cls2 = cls1 as Class2;
if (cls2!=null)
    System.Console.WriteLine ("OK");
else
    System.Console.WriteLine ("error!");

Complementary: In contrast, the is needs to do a type check of two objects, while the as requires an object type check, a null check, and a null check cost less than the object type check. The method relative to as is more efficient.

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.