How to avoid exceptions during type conversion

Source: Internet
Author: User

Analyze problems

Programmers often face some type conversion tasks, some of which are deterministic and convertible. For example, a type object is converted into a base class object, while some are tentative, for example, if you want to convert an object referenced by a base class to a subclass, the programmer should be prepared to catch exceptions when such an attempt is executed.

When an incorrect type is converted into a row, an invalidcastexception occurs. Programmers sometimes use try and catch blocks to perform some tentative type conversion. Such code has no errors, however, the performance is quite poor. An exception is a resource-consuming mechanism. When an exception is thrown, the exception stack will be created and the exception information will be loaded. These work costs are usually relatively high, in addition, this information is meaningless during the trial conversion. Therefore, C # provides another syntax for trial type conversion, that is, the work done by the keyword is and.

The is statement is used to determine whether an object can be converted to another object. If yes, true is returned. If no, false is returned. The as statement implements a similar function. It checks the object for trial. If it can be converted to a specified object, the converted reference is returned. If not, null is returned.

Answer

Using the is and as statements instead of forced conversion can effectively avoid invalidcastexcepiton exceptions, and the execution efficiency is relatively high. The reader should use the is or as statement instead of the direct use of forced 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.