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();
After executing the above program we will not encounter any run time exception but we will get a very surprising result. Please check the below snapshot for the result.
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)
- {
-
- }
Please check the exception details,
In a simple words, the use of the checked keyword is for when we want to ensure the left-hand side data type is not getting overflow.
Let's discuss unchecked keyword , the unchecked almost behaves in the same way.
Please check the below code snippet and snapshot.
- const int a = 2147483647;
- const int b = 2147483647;
- int sum = (a + b);
When we build the above program we will get a compile-time error because compiler itself validates when we are dealing with constant variables.
To avoid this kind of situation we can use the unchecked keyword. Please check the below code snippet. We can run the below code without any exception.
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
-
- const int a = 2147483647;
- const int b = 2147483647;
- var sum = unchecked(a + b);
- Console.WriteLine(sum);
- Console.ReadLine();
- }
- catch(Exception ex)
- {
-
- }
-
- }
- }
Summary
In this blog we discussed checked and unchecked keyword with a simple program.