C # medium "is" vs ""

Source: Internet
Author: User
In data type conversion, C # is stricter than other languages, and explicit data conversion is required.
For ease of operation, C # also provides an is Operator for conversion, which automatically checks whether the current situation is compatible with the type and returns the result. And it does not throw an exception. If the object reference is null, the is always returns false.

If (Cls1 Is Class2)
{
Class2 cls2=(Class2) cls1;
}
Else
System. Console. writeline ( " Error 2! " );

I usually use this method for type conversion, but today I readArticle, Compared to another method, The as operator is converted to know that as can slightly improve the performance than is.

Class2 cls2 = Cls1 As Class2;
If (Cls2 ! = Null )
System. Console. writeline ( " OK " );
Else
System. Console. writeline ( " Error! " );

As is slightly different. It checks whether the referenced object is compatible. If it is not compatible, null is returned. Therefore, null is required.

 

Comparing the two methods, is requires two object type checks, while as requires an object type check and a null check. The null check overhead is less than the object type check. It is more efficient than the as method.

It seems that some of the daily writing habitsCodeWe can always find improvements. Isn't it better to use new methods as a habit?

The as operator is used to explicitly convert a value to a specified reference type through reference conversion or packing conversion. Unlike Explicit conversions, as does not produce any exceptions. If the conversion fails, the result value is null. E is an expression and T is a reference type. The type of the returned value is always T type, and the result is always a value.

For example, when youProgramWrite the following statement:

String S = 'A' as string

Although the character type cannot be converted to the string type, the program can still be compiled, but there is a warning:

The given expression is never of the provided ('string') type.

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.