Objective
In this article, I will discuss about Checked and unchecked keyword and conversions in C#.
Consider the below code
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication7
{
class Program
{
static void 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.
- We are increasing the number by 1. Now here it should get overflow because an integer variable cannot hold a number greater than 2147483647
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 CHECKED keyword. Just put all the codes in between checked block
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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication7
{
class Program
{
static void 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
You can change the behavior of compiler from checked to unchecked through command prompt.