Read the Classics-"CLR via C #" (Jeffrey Richter) Notes _ primitive Type (iii)

Source: Internet
Author: User

"Checked and unchecked primitive type operations"

1. First mode of Use

unchecked ((UInt32) (-1//OK, will not throw abnormal  checked)); // Throw OverflowException Exception

2. Second mode of Use

checked {// start a checked block      - ;      ); // the expression will overflow check } // end a checked block

Simplified notation

Checked {    ;     B +=;}    

Note

The checked operator and the checked statement- The only function that determines which version of the add, subtract, multiply, and data conversion Il directives are generated , so calling a method in a checked operator or statement does not have any effect on the method, as in the following example:

Checked {   // assume SomeMethod attempts to load 400 into a byte   somemethod (+////// However, this is not relevant to the current checked statement }        

Recommendations

1. Try to use a signed numeric type instead of an unsigned numeric type.

2. In the code, place the part that you do not want to overflow in a checked block while capturing OverflowException.

3. In the code, the code that will allow the overflow to appear is placed in a unchecked block.

4. For any code that does not use checked and unchecked, assume that you want an exception to be thrown when an overflow occurs, and that the overflow should be treated as a bug.

Read the Classics-"CLR via C #" (Jeffrey Richter) Notes _ primitive Type (iii)

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.