Differences between as and is in. net

Source: Internet
Author: User

1.

It is used to perform conversions between compatible reference types. The as operator is similar to a forced conversion operation. However, if the conversion is not feasible, the as returns null instead of an exception. More strictly speaking, expression as type is equivalent to expression is type? (Type) expression: (type) null, only the expression is calculated once. Note that the as operator only performs reference conversion and packing conversion. The as operator cannot perform other conversions, such as user-defined conversions. cast expressions should be used to perform conversions that are not performed by the as operator, if the type of the object to be converted belongs to the conversion target type or the derived type of the conversion target type, the conversion operation can be successful.

Efficiency:

When the as operator is used for type conversion, first determine the type of the current object and convert the object only when the type meets the requirements, is to use the current object to directly convert, and to ensure successful conversion, add try-catch. in addition, no new object is generated [null is returned when the operation fails ]. Comparatively speaking, the as efficiency is high, and it is safe to use as for type conversion. Example: e. Item. DataItem as DataRowView (DataRowView) e. Item. DataItem

2. is

Check whether the object is compatible with the given type, for example, if (obj is string ){}. If the provided expression is not empty and the provided object can be forcibly converted to the provided type without causing an exception, the is expression returns true. If the expression is always true or false, the is keyword will cause a warning during compilation. However, type compatibility is usually calculated during runtime. The is operator cannot be overloaded. Note that the is operator only considers reference conversion, boxing conversion, and unboxing conversion.

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.