BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Checked and Unchecked Arithmetic

Arithmetic operations are limited to some extent by the type of variable being acted upon. In some cases values can exceed their data type limits and provide incorrect, and potentially dangerous answers. This is prevented by using checked arithmetic.

Overflows

When a value exceeds the limitations of a data type, it is said to overflow. This can be an inconvenience where unexpected, causing incorrect results from calculations. It can even be dangerous, particularly when using unsafe code, creating a buffer overrun vulnerability that can be exploited by malicious software.

Unchecked Arithmetic

When using the default C# compiler options, arithmetic is unchecked. This means that any overflowing data from arithmetic operations is simply truncated. In the following sample code this is demonstrated by setting an integer to its maximum value, then incrementing it. The resultant value is truncated and rather than being a larger number is actually the smallest permissible integer value.

int i = int.MaxValue;
Console.WriteLine(i);

i++;
Console.WriteLine(i);

/* OUTPUT

2147483647
-2147483648

*/

Checked Arithmetic

To prevent the incorrect or dangerous results of unchecked calculations, checked arithmetic can be used instead. One way to achieve this is to use the "checked" keyword for specific sections of code. This keyword uses a code block to surround a series of items that should be processed in this way. If an overflow occurs within a checked code block, an exception of the type System.OverflowException is thrown.

checked
{
    int i = int.MaxValue;
    Console.WriteLine(i);

    i++;
    Console.WriteLine(i);
}

Single statements may also be checked using the checked keyword, with the expression to be evaluated within parentheses. The following code is functionally the same as the previous example.

int i = int.MaxValue;
Console.WriteLine(i);

i = checked(i + 1);
Console.WriteLine(i);

Checked Compilation

If most or all of your code should be executed using checked arithmetic, the compilation process can be adjusted. For users of Visual Studio, the "Check for arithmetic overflow/underflow" option can be selected from the advanced build options in a project's properties.

If compiling from the command line, the "/checked+" switch can be used for checked arithmetic and "/checked-" for unchecked arithmetic by default.

Unchecked Code Blocks

In some circumstances you will wish to have a project that is compiled using checked arithmetic by default but you may still want to specify some sections of unchecked code. This is achieved using the "unchecked" keyword. The syntax is similar to that of the "checked keyword".

unchecked
{
    int i = int.MaxValue;
    Console.WriteLine(i);

    i++;
    Console.WriteLine(i);
}
23 May 2008