Introduction
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.
- int a = Int32.MaxValue;
- int b = Int32.MaxValue;
Now, I want to add this into some other variable, as shown below.
- 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.
- using System;
- namespace mathfunction {
- public class csharpdemo {
- public static void Main() {
- int a = Int32.MaxValue;
- int b = Int32.MaxValue;
- int c = a + b; // at this point of code , compiler ignore the code and move ahead . however this is wrong.
- Console.WriteLine("The sum of a+b is :" + c);
- Console.Read();
- }
- }
- }
Thus decorate the a+b into checked keyword, as shown below.
- 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.
- using System;
- namespace mathfunction {
- public class csharpdemo {
- public static void Main() {
- const int a = Int32.MaxValue;
- const int b = Int32.MaxValue;
- int c = checked(a + b); // at this point of code , checked will not work anymore . code throw the error.
- Console.WriteLine("The sum of a+b is :" + c);
- Console.Read();
- }
- }
- }
In order to ignore these kind of errors, it can use the unchecked keyword. Let’s see the example.
- 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 .
Your comments and feedback are always welcome.

Join the conversation! Your thoughts help the community grow.