Introduction
In this blog, we are discussing the use of the checked and unchecked keyword.
Let me create a small console application to understand the real use of the checked and unchecked keyword.
Sometimes what happens we will move data which is more than data type. For example, let's consider integer.
What is the maximum value integer can hold? Please check the below and code output.
- var sum = int.MaxValue;
- Console.WriteLine(sum);
- Console.ReadLine();
Please check the below snapshot for the result.
Let's perform the addition operation with the maximum value of the integer data type.
Please check the below code snippet.
- int a = 2147483647;
- int b = 2147483647;
- int sum = (a + b);
- Console.WriteLine(sum);
- Console.ReadLine();
We can see in the above snapshot sum variable holds the -2 value due to overflow. When we are doing an arithmetic operation in our project this type of answer leads to a production bug. To avoid this type of situation at least we should log the exception correctly. Please check the below code and exception details.
- try
- {
- int a = 2147483647;
- int b = 2147483647;
- int sum = (a + b);
- Console.WriteLine(sum);
- Console.ReadLine();
- }
- catch(Exception ex)
- {
- }

Join the conversation! Your thoughts help the community grow.