C # By default, if the value of a constant expression exceeds the maximum value of the target type, a compilation error will result.
If the target data type cannot hold data from a very few expressions, the data is truncated when it is assigned.
Class Program {static void Main (string[] args) {int n = Int. maxvalue;//n=2147483647 n = n + 1; System.Console.WriteLine (n); } }
At this point the available memory stores data to interpret, before int. MaxValue in memory is 32 bit 1, since adding 1 to 32 bit 0, at this time 0 is considered to be a minus sign, so it will get-2147483648.
Placing the above code in the checked block will cause the System.OverflowException type to be thrown.
Class Program {static void Main (string[] args) {checked {int m = Int. MaxValue; m = m + 1; System.Console.WriteLine (m); } } }
A variable in C # that is placed in a checked block throws an exception if the assignment of an overflow occurs at run time.
The unchecked is used to cancel overflow checking of integer arithmetic operations and conversions.
The above is the C # difficulty one by one (7): checked and unchecked content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!