Saturday, February 10, 2007

Checked and Unchecked keyword

When reading an article I noticed the checked keyword for the first time.

The checked and unchecked keywords are used to control the overflow-checking for integral-type arithmetic operations and conversions. It can be used as an operator or a statement.

In a checked context, if an expression produces a value that is outside the range of the destination type, an exception will be thrown.

In an unchecked context, if an expression produces a value that is outside the range of the destination type, the value will be truncated.

The following sample shows the use of the checked keyword which forces an exception when an overflow occurs:
static void Main(string[] args)
{
int x = int.MaxValue;
int y = int.MaxValue;
int z = 0;

try
{
// Checked in its statement form:
checked
{
z = x + y;
}
}

catch (System.OverflowException e)
{
Console.WriteLine(e.Message);
}

Console.WriteLine(z.ToString());
Console.ReadLine();
}

Result:
Arithmetic operation resulted in an overflow.
0


The following sample shows the use of the unchecked keyword which truncates the result when an overflow occurs:


static void Main(string[] args)
{
int x = int.MaxValue;
int y = int.MaxValue;
int z = 0;

try
{
// Unchecked in the operator form:
z = unchecked(x + y);
}

catch (System.OverflowException e)
{
Console.WriteLine(e.Message);
}

Console.WriteLine(z.ToString());
Console.ReadLine();
}


Result:
-2

REMARKS: If neither checked nor unchecked is used, a constant expression uses the default overflow checking at compile time, which is checked. Otherwise, if the expression is non-constant, the run-time overflow checking depends on other factors such as compiler options and environment configuration.

0 comments: