Let's start with definitions first. As per MSDN:

The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.
And:
The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.
Here, overflow checking means that when the value of an integral-type exceeds its range, it does not raise an exception, instead it will provide unexpected results. Let's discuss this with an example of integers.

We know that the range on an integer is 2147483647. Let's see what happens when we try to add more to it, say add 50 to it. See the code below:

cs code

It gives the compile time error:

Error 3 The operation overflows at compile time in checked mode ...\checked\Program.cs 23 29 checked.

So, at least we cannot do this directly. Also, in most cases, we work with values from a database. So we fetch them, store them in variables and then perform any operations on it. In such a case, there will be no compile time or run time error, instead will see unexpected results. Let's check and see what happens:

checked program

As we discussed, an unexpected result. The unexpected result is generated in a pattern. The add operation adds a given number up-to maximum possible value of its range. Then it resets itself to its minimum value of its range and then starts adding again. In our case, we were adding 50 to 2147483647. So let's see how it works. We can handle this overflow of the value using the checked keyword. It will not give the correct result but at least it will give you an exception of the type System.OverflowException and you can easily identify the issue. So apply the checked keyword, wrap the code in a try-catch block and perform the alternate operation in the catch block. Let's change the code accordingly now:

program code and output

So you can now at least handle such kind of situation, instead of giving incorrect results to the user.

Now, earlier in our discussion, we discussed that directly we cannot add more value to the maximum value of an integer. What if we need to do this. This is where we can use the unchecked keyword. Just use the same code with the unchecked keyword and it will compile and will even run to give the results. See the code below:

checked code

So to summarize the discussion: code

So this about the use of checked and unchecked keywords. I hope you enjoyed reading it!