When we do conversion in c# , sometime conversions are not checked. C# compiler may not check the conversion and truncate the result. So Checked keyword helps us in doing that.
Objective
In this article, I will discuss about Checked and unchecked keyword and conversions in C#.
Consider the below code
Program.cs
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespace ConsoleApplication7
{
classProgram
{
staticvoid Main(string[] args)
{
int number = int.MaxValue;
number = number + 1;
Console.WriteLine(number);
Console.Read();
}
}
}
Now, if you see the above code
- We are taking maximum integer value in a variable. And that is 2147483647.
int number = int.MaxValue;
- We are increasing the number by 1. Now here it should get overflow because an integer variable cannot hold a number greater than 2147483647.
number = number + 1;
So, now data will overflow and truncate during the assignment.
So, as the output we will get

If you notice above output, number assigned is truncated to -2147483647
It happened because compiler is doing unchecked compilation
So forcefully do the checked compilation, we will use CHECKEDkeyword. Just put all the codes in between checked block
static void Main(string[] args)
{
checked
{
// Your Code for checked compilation
}
}
So, now to avoid truncating during overflow assignment, we need to put our code in between Checked block.
So, modify the above code as below
Programs.cs
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespace ConsoleApplication7
{
classProgram
{
staticvoid Main(string[] args)
{
checked
{
int number = int.MaxValue;
number = number + 1;
Console.WriteLine(number);
Console.Read();
}
}
}
}
Now if you run the above code, you will get the below error.

It shows if the code is in checked block then rather than truncating at overflow, compiler is throwing an exception.
If we are doing checked compilation then to override that, we can put our code in Unchecked Block
unchecked
{
// Your Code to override
// Checked compilation
}
You can change the behavior of compiler from checked to unchecked through command prompt.