Checked And UnChecked Keywords In C#

In this tutorial I will explain about little known keywords called checked and unchecked in C#.

I came to know about these keywords accidentally, I will share the story with you people.

One of my friends’s project simple arithmetic addition failing and returning some garbage value (No exceptions). The code is something like this

NumberOfOrders = NumberOfOrders+newOrders; 
Console.WriteLine(NumberOfOrders);

 

CheckedandUnchecked

CheckedandUnchecked

 

The NumberOfOrders and newOrders are integer variables and after couple of minutes of investigation we came to know that it got reached it’s maximum value, To our surprise there is no compile time error as well as runtime error.

int x = int.MaxValue;   //2147483647
int y = x + x;          //No Exception
Console.WriteLine(y);   //Prints -2

 

Then we came to know about checked and unchecked keywords.

In C# language we have two types of execution contexts checked and unchecked(Which is very new to me). And this context is depend on compiler most of the cases it’s unchecked.

In Unchecked context arithmetic exceptions are ignored and result will be truncated. The following operations are affected due to this contexts

  • Statements using ++       – (unary)   +   –   *   /  on integral types(byte ,char, short, int, long variables types).
  • Explicit numeric conversions between integral types.

So the correct code will be

checked
{
      int x = int.MaxValue;
      int y = x + x;
      Console.WriteLine(y);
}

 

Just include the code in “checked” block. And now at runtime code will through arithmetic overflow exception. So to handle the exception I will add try catch blocks. So the final code is

            checked
            {
                try
                {
                    int x = int.MaxValue;
                    int y = x + x;
                    Console.WriteLine(y);
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                }
            }

 

Now you might be thinking that why we required two contexts , instead we can maintain only one checked context. In real world projects chances of getting arithmetic overflow exceptions are very low(that’s why default context is unchecked).

So checking for exceptions for each such statements at runtime will be extra overhead for CLR. So the code that might cause overflow exception should be executed in a checked context.Remaining code will be executed in unchecked environment for which performance is priority

The ideal solution for this is to write code like below

            checked
            {
                // Code that might cause overflow should be executed in a checkd
                // environment. 
                try
                {
                    int x = int.MaxValue;
                    int y = x + x;
                    Console.WriteLine(y);
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                }
                unchecked
                {
                    /*
                     this block will contain normal statements which will not cause overflow exceptions
                     * And performence will be priority her.
                     */
                    int z = 2 + 10;
                    Console.WriteLine(z);
                }
                // checked code here. 
            }

 

 Checked and Unchecked contexts with Constant variables:

For constant variables compiler itself will throw the error “Overflow in constant value computation”.

            const int a = int.MaxValue;
            int b = a + 10;

 

The above code will not compile and throws the error. And If you want to skip the exception just execute them in unchecked context as shown below

            unchecked
            {
                const int a = int.MaxValue;
                int b = a + 10;
                //Some garbage value will be stored in b
            }

 

We can specify the context for single statements also as shown below.Just add the checked or unchecked keyword before the statements and enclose the statements in brackets.

            int z1 = int.MaxValue;
            int z2 = checked(z1 + z1);

 

I hope you’ve enjoyed this article and that it gives you more ideas on checked and unchecked keywords in C# .If so share this post with your friends, follow me on social networks and also join our mailing list.