Checked And Unchecked Keyword In C#

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.  
  1. var sum = int.MaxValue;  
  2. Console.WriteLine(sum);  
  3. 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.
  1. int a = 2147483647;  
  2. int b = 2147483647;  
  3. int sum = (a + b);  
  4. Console.WriteLine(sum);  
  5. 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.
  1. try  
  2. {  
  3.    int a = 2147483647;  
  4.    int b = 2147483647;  
  5.    int sum = (a + b);  
  6.    Console.WriteLine(sum);  
  7.    Console.ReadLine();  
  8. }  
  9. catch(Exception ex)  
  10. {  
  11.   
  12. }  
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. 
  1. const   int a = 2147483647;  
  2. const  int b = 2147483647;  
  3.  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. 
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             try  
  6.             {  
  7.                  
  8.               const   int a = 2147483647;  
  9.               const  int b = 2147483647;  
  10.               var sum = unchecked(a + b);  
  11.               Console.WriteLine(sum);  
  12.               Console.ReadLine();  
  13.             }  
  14.             catch(Exception ex)  
  15.             {  
  16.   
  17.             }  
  18.               
  19.         }  
  20.     }  

Summary

 
In this blog we discussed checked and unchecked keyword with a simple program.