|
1
intermediate
0
beginner
0
advanced
|
|||
|
||||
|
A checked operator tells the runtime to throw an OverflowException when an arithmetic operation results in a value which is outside the bounds of that type. The default behaviour is not to throw an exception, but can result in incorrect result due to wrapping around of values. Following code illustrates the wrapping around during an overflow: static void Main() { int i = int.MaxValue; i = i + 1; Console.WriteLine(i); } The above code outputs -2147483648, which is clearly wrong, and is especially dangerous for financial applications. If we want such overflows to throw an exception, we can use the checked keyword as illustrated below: static void Main() { int i = int.MaxValue; i = checked(i + 1); Console.WriteLine(i); } The above code throws an exception: System.OverflowException: Arithmetic operation resulted in an overflow. If we want all code inside a block to be "checked", you can surround the block with the "checked" keyword: checked { // multiple arithmetic operations }Also if we want your entire application's arithmetic operations to be checked by default, you can enable it using the /checked+ switch in the compiler's command line arguments. You can then use the unchecked keyword to specifically ignore overflows if required. Note that if any compile time expressions overflow, compiler error is generator irrespective of the switch. You need to explicitly use the unchecked operator in such cases. int i = int.MaxValue + 1; //Compiler error int i = unchecked(int.MaxValue + 1) //Overflows but no error |
|||
|
||||