This post explains about checked and unchecked keywords in C#. In arithmetic calculations when constants are involved compiler detects the overflows in the data types. For example look at the following code.
The above will generate a compile time error. But the following won’t and it will give an output –2,147,483,639
Because the compiler does not detect the overflows when non constants are are involved in the expression.
The above will not even raise an OverflowException. To make sure that the above is validated in runtime, we can use the checked keyword as a block or in line.
As a block
Since checked keyword validates against the overflows and throws an exception, it has a performance hit. So when you are sure that the expression is not going to cause an OverflowException it is better not use the checked keyword.
unchecked does the opposite of the checked. It mainly instructs the compiler not to do the validation for an expression. The following would generate a compile time error if it is not enclosed with the unchecked block. As checked keyword unchecked keyword can also be used in blocks and inline.