Check operator tells the runtime to generate an OverflowException rather than overflowing silently when an integral expression or statement exceeds the arithmetic limits of that type.
The checked operator affects expressions with the ++,–,+,-,*,/ and explicit conversion operators between integral types. Checked can be used around either an expression or a statement block.
int a = 1000000;
int b = 1000000;
int c = checked(a*b); //Checks just the expression.
checked //Checks all expressions in statement block.
c = a * b;
If we are using a compiler with the /checked command line then this will check all the expressions in the program.
In such a case if we need to disable overflow checking just for specific expressions or statements, we can do so with the unchecked operator.
int x = int.MaxValue;
int y = unchecked (x + 1); //Leaves the expression from checking.
unchecked //Leaves all the expressions inside the block from checking.
int z = x + 1;
Against all the above statements let’s say we have a constant expression then the overflow will be evaluated at the compile time itself unless we are applying the unchecked operator.
int x = int.MaxValue + 1; //Compile time error.
int y = unchecked (int.MaxValue + 1); //No errors.