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.
1: // int range is from -2,147,483,648 to 2,147,483,647
2: int i = 2147483647 + 10;
The above will generate a compile time error. But the following won’t and it will give an output –2,147,483,639
1: int ten = 10;
2: int i = 2147483647;
3: Console.WriteLine(i + ten);
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
3: Console.WriteLine(i + 10);
1: Console.WriteLine(checked(i + 10));
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.
3: int a = 2147483647 + 10;