Basics of C#: Checked and Unchecked Conversions

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

1. We are taking maximum integer value in a variable. And that is 2147483647.

clip_image001

2. We are increasing the number by 1. Now here it should get overflow because an integer variable cannot hold a number greater than 2147483647

clip_image002

So, now data will overflow and truncate during the assignment.

So, as the output we will get

clip_image004

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

clip_image006

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.

clip_image007

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

clip_image009

You can change the behavior of compiler from checked to unchecked through command prompt.

3 responses to “Basics of C#: Checked and Unchecked Conversions”

  1. Good work friend.

    Cheers.

  2. Dhananjay Kumar

    Glad that it is useful to you !!!

  3. Good one man

    regards
    Lohith

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com