Thursday 19 February 2015

Checked and Unchecked operators in C#

This post demonstrates checked and unchecked operators in C#. While working with arithmetic operators (+, -, *, /), there is a possibility of overflow.
The arithmetic operations produce results outside the range of possible values which causes an exception depends on the execution context, which can be checked or unchecked.
C# gives an option whether to handle the exception or ignore the exception. We are achieving these two contexts by making use of checked and unchecked operators.
Warning - In checked or unchecked context; integer division by zero or decimal division by zero always throws an exception Divide By Zero Exception.

Checked -

In simple, this operator is used to throw Overflow Exception. This keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.
If we don’t specify checked/unchecked, the execution depends on the compiler options. The following operations are affected by the checked and unchecked keywords

  • Expressions using the operators ++, --, - (unary) and arithmetic operators.
  • Explicit numeric conversions between integral types. (int, long to short)

The following are the different ways to enable overflow exception in your application – Enable overflow checking for complete application - Open the project’s Properties page. (Right click on your project -> Properties) Select Build -> Click on Advanced button -> Check the box Check for arithmetic overflow/underflow property  

Enable overflow checking for an expression -
 
//checked for an expression
checked(expression)

  Enable overflow checking for a block of statements -
 
//checked for a block
checked
{
   statement1;
   statement2;
   ...
}
 
Note : By default non-constant expressions (expressions that contain non-constant terms e.g. expression ‘a= 10+ b’ where b is a non-constant term) are not checked for overflow by the compiler at compile time and run time until unless we include the checked keyword.

For Example -

// max value of integer is 2147483647
//This statement causes compiler error beacuse of constant expression
//int i1 = 2147483647 + 10; 

// No compiler error because of non-constant expression
int ten = 10;
int i2 = 2147483647 + ten;

// By default, the overflow in the previous statement also does 
// not cause a run-time exception. 
//The following line displays -2,147,483,639 as the sum of 2,147,483,647 and 10.
Console.WriteLine(i2);
 

Unchecked -

In simple, this operator is used to ignore Overflow Exception. This keyword is used to ignore the overflow-checking for integral-type arithmetic operations and conversions.
In this context, the most significant bits of the result are discarded and execution continues.

Disable overflow checking for an expression -
 
//unchecked for an expression
unchecked(expression)
 
Disable overflow checking for a block of statements -
 
//unchecked for a block
unchecked
{
   statement1;
   statement2;
   ...
}
 

Try This Sample Code -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OverFlowExample
{
    class OverFlowExample
    {
        // max value of integer
        static int maxInt = 2147483647;

        // checked expression. 
        static int CheckOverflow()
        {
            int x = 0;
            try
            {
                // The following line raises an exception
                x = checked(maxInt + 10);
            }
            catch (System.OverflowException e)
            {
                //information about the error.
                Console.WriteLine("CHECKED:  " + e.ToString());
            }
            // The value of x is 0. 
            return x;
        }

        //unchecked expression. 
        static int UncheckOverflow()
        {
            int x = 0;
            try
            {
                // unchecked and will not raise an exception.
                x = maxInt + 10;
            }
            catch (System.OverflowException e)
            {
                // No exception;the following line will not be executed.
                Console.WriteLine("UNCHECKED:  " + e.ToString());
            }
            //overflow is suppressed
            // the sum of 2147483647 + 10 is returned as -2147483639. 
            return x;
        }

        static void Main()
        {
            Console.WriteLine("\nCHECKED output: {0}",
                              CheckOverflow());
            Console.WriteLine("UNCHECKED output: {0}",
                              UncheckOverflow());
        }          
    }
}
/*
       Output:
       CHECKED:  System.OverflowException: Arithmetic operation resulted
       in an overflow.
          at ConsoleApplication1.OverFlowExample.CheckOverflow() 

       CHECKED output: 0
       UNCHECKED output: -2147483639
*/

Please share your thoughts on this post in the comments section.

Karthik Byggari

Author & Editor

Computer Science graduate, Techie, Founder of logicallyproven, Love to Share and Read About pprogramming related things.

0 comments:

Post a Comment

 
biz.