Checked And Unchecked In C#

Introduction

In this blog, we will learn what the uses of checked and unchecked keywords in C# are.

Checked - This is the keyword and a code marker in C# laguage. It means in some of the cases, C# compiler doesn’t care about the code exception because of the default behavior and ignores the unexpected code without throwing an error.

Let’s see what I am trying to explain in a real situation.

  1. int a = Int32.MaxValue;  
  2. int b = Int32.MaxValue;  

Now, I want to add this into some other variable, as shown below.

  1. int c = a+b ; // Here the code will execute but statement is wrong .  

Suppose int can take 2,147,483,647. This limits the value only, so how can we add two maximum values into a variable?

Thus, we have the checked keyword. To force the compiler, check the code and raise the overflow exception.

Let’s see the concept in the code.

  1. using System;  
  2. namespace mathfunction {  
  3.     public class csharpdemo {  
  4.         public static void Main() {  
  5.             int a = Int32.MaxValue;  
  6.             int b = Int32.MaxValue;  
  7.             int c = a + b; // at this point of code , compiler ignore the code and move ahead . however this is wrong.  
  8.             Console.WriteLine("The sum of a+b is :" + c);  
  9.             Console.Read();  
  10.         }  
  11.     }  
  12. }  

Output

Thus decorate the a+b into checked keyword, as shown below.

  1. Int c = checked(a+b);  

Now, you can see the result here. We are getting the proper exception through checked keyword.

Unchecked - Unchecked is also a code marker but it works in some special cases. This is useful in some static or fixed value.

Let’s see the example of the same code.

  1. using System;  
  2. namespace mathfunction {  
  3.     public class csharpdemo {  
  4.         public static void Main() {  
  5.             const int a = Int32.MaxValue;  
  6.             const int b = Int32.MaxValue;  
  7.             int c = checked(a + b); // at this point of code , checked will not work anymore . code throw the error.  
  8.             Console.WriteLine("The sum of a+b is :" + c);  
  9.             Console.Read();  
  10.         }  
  11.     }  
  12. }  

In order to ignore these kind of errors, it can use the unchecked keyword. Let’s see the example.

  1. int c = unchecked( a + b); // at this point of code , compiler will uncheck the code and doesn’t throw any kind of errors .  

Thus, let's conclude this article in short.

  • Checked
    This is a keyword and code marker to force compiler to check the unexpected code used in program.

  • Unchecked
    This is a keyword and code marker and to force compiler to ignore the unexpected code or the data type used in the program . 
I hope, this article will be useful for you guys. Thanks for your time and patientce for reading this article . 

Your comments and feedback are always welcome.