The checked operator tells the runtime to generate an OverflowException in case of Overflow.
The checked operator affects expressions with the ++, --, +, -, *, /, and explicit conversion operators between integral types.
The checked operator has no effect on the double and float types.
C# double and float types overflow to special "infinite" values.
decimal type is always checked.
checked can be used around either an expression or a statement block. For example:
int a = 1000100; int b = 1000200; int c = checked (a * b); // Checks just the expression. checked // Checks all expressions { // in statement block. c = a * b; }
You can turn on arithmetic overflow checking by compiling with the /checked+ command-line switch.
To disable overflow checking for specific expressions or statements, use unchecked operator.
For example, the following code will not throw exceptions-even if compiled with /checked+:
int x = int.MaxValue; int y = unchecked (x + 1); unchecked { int z = x + 1; }