"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)