Checked and Unchecked operators using an example

 

About Checked and Unchecked operator

Checked and unchecked are operators of C#. Checked and Unchecked operators enforce CLR (Common Language Runtime) to handle stack overflow control.These operators checks code block which can cause overflow in an application.

Checked Operators

The checked operator evaluates a block of code in a checked context and enforces overflow through an exception if an overflow occurs.

Syntax of Checked Operator

 
static void Main(string[] args){

 checked{
    //Block of code or expression
    int x = 1000000 * 2000000;
 }

}   

Unchecked Operators

The checked operator evaluates a block of code in an unchecked context and does not through overflow exception if an overflow occurs.

Sometimes it might through negative integral output or wrong output (in terms of calculation).

Syntax of UnChecked Operator

 
static void Main(string[] args){

 unchecked{
//Block of code or expression
 int x = 1000000 * 2000000;
 }

}   

Demonstrate Checked and Unchecked operators using an example

Now let's demonstrate a simple example using console application. In this example we will use int (Int32) variable to check overflow in an application.

Step 1: Create Console Application

 
      class Program
      {
          static void Main(string[] args)
	    {
		
          }
	}

Step 2: Use int (Int32) variable to check for overflow.

For this step we will use integer variable "inttestVariable" and assign a highest value to it i.e. highest Int32 bit value which is 2147483647.

 
class Program
      {
          static void Main(string[] args)
	    {
		int inttestVariable = 2147483647;
            Console.WriteLine("Our current int value is... " + inttestVariable);
          }
	}

To test your "int" size, type i.e. whether its 32 bit or 64 bit and range you can use operator


Typeof - Get the type of a data type.
Sizeof - Get the total size of a data type.
Minvalue - Get minimum value of a data type
Maxvalue - Get maximum value of data type.

As we have shown in below code.

 
class Program
      {
          static void Main(string[] args)
	    {
		Console.WriteLine("{0}: bytes: {1}, range: [{2},{3}]", typeof(int).ToString(), sizeof(int), int.MinValue, int.MaxValue);
          }
	}

Now coming back to checked and unchecked operator. Next step let’s use checked operator and increment the default value of an integer variable "inttestVariable" in the code block of checked operator.

 
class Program
      {
          static void Main(string[] args)
	    {
		int inttestVariable = 2147483647;
            Console.WriteLine("Our current int value is... " + inttestVariable);

         checked{

             Console.WriteLine("\n");
             inttestVariable++;
             Console.WriteLine("Checked Value becomes... " + inttestVariable);

            }

          }
	}

If you see above code we have incremented the integer value by +1 means it's an overflow in an application. Because the maximum value of integer is 2147483647.It will cause a stack overflow exception error. Let's display output and see the error.

Display Output

For Unchecked operator

Now let's change the operator replacing checked with unchecked and check the output.

 
class Program
      {
          static void Main(string[] args)
	    {
		int inttestVariable = 2147483647;
            Console.WriteLine("Our current int value is... " + inttestVariable);

         unchecked{

             Console.WriteLine("\n");
             inttestVariable++;
             Console.WriteLine("Checked Value becomes... " + inttestVariable);

            }

          }
	}

As you see from above code block of unchecked operator is that it does not thrown an exception error but it has shown negative output or wrong in calculation.

So it is conclude that checked operator checks the block of code if arithmetic calculation or value is overflow in an application then it will throw up an overflow exception error while unchecked operator does not throw up overflow exception error.

I hope that you have understood Checked and Unchecked operators. If you still have more doubts kindly let me know through your comments. If you like this article share it with your friends.

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
Jul
07
2013

Understanding Switch Statement with the help of an example

CLICK TO READ FULL ARTICLE

Views - 6399 |Category - C#

Jul
05
2013

What are structures? Differentiate between structures and classes

CLICK TO READ FULL ARTICLE

Views - 6701 |Category - C#

Jun
30
2013

Understanding the concept of pass by value and pass by reference with an example?

CLICK TO READ FULL ARTICLE

Views - 8343 |Category - C#

Jun
25
2013

Sealed Classes in C# with an example and explanation

CLICK TO READ FULL ARTICLE

Views - 32371 |Category - C#

Jun
22
2013

Understanding the Relationships - Inheritance, Association, Aggregation and Composition in C#

CLICK TO READ FULL ARTICLE

Views - 34374 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

v47md

 

 
Comments

Posted by Nikhil on 2013-07-19

Very Very helpful.. I feel like learning more and more.. From the scratch.. I have a lot of interest to learn ASP.NET C#.. I want to be technically strong.. I don't know much about coding syntax and all.. and how objects are handled.. These examples and explanation to each one of them help me a lot.. Thanks!