Posted by: Cirilo Meggiolaro | 11/6/2008

Tip of the day #23 – Checked and unchecked keywords

Today’s tip is about keywords.

The C# keyword checked can be used to enable overflow exception checking in compile time for arithmetic operations and conversions between values in constants. The keyword also overrides any configuration made at the application level or build options related to code checking.

public static void MyMethod()
{
const short number1 = short.MaxValue;
const short number2 = short.MaxValue;
int result = 0;

try
{
result = checked((short)(number1 + number2));
Console.WriteLine(result);
}
catch (OverflowException)
{
Console.WriteLine(“Overflow exception.”);
}
}
Code 1 – This code generates an error in compile time.

In runtime the checked keyword will raise an OverflowException when the result exceeds the maximum value allowed for a specific type like in the following code:

public static void MyMethod()
{
short number1 = short.MaxValue;
short number2 = short.MaxValue;
int result = 0;

try
{
result = checked((short)(number1 + number2));
Console.WriteLine(result);
}
catch (OverflowException)
{
Console.WriteLine(“Overflow exception.”);
}
}

Code 2 – This code generates an error in runtime.

The unchecked keyword acts in the opposite way, suppressing the exceptions in both compile time and runtime. Use carefully because results will be truncated.

Advertisements

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 )

Google+ photo

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

Connecting to %s

Categories

%d bloggers like this: