Checked and Unchecked Keywords in C#

Description

The checked and unchecked keywords in C# can help to detect/prevent overflows.

The checked keyword is used to check for overflows in arithmetic operations. By default, the compiler will detect overflows but only if constant values will exceed the size of the used type. If variables instead of constants are used, the compiler won’t detect the overflow and won’t generate an error.

The unchecked keyword is used to suppress overflow checking in arithmetic operations. In an unchecked context, even if two or more constants would exceed the type’s size, the overflow will not be signaled at compile time by an error.

Usage

Let’s see the following scenario:

int maxValue = int.MaxValue; //2147483647
int overflow = int.MaxValue + 10; //flagged at compile time (constants)
int overflow = maxValue + 10; //-2147483639 - legal (variables)

By default, there is no overflow checking so the last statement is legal, producing the -2147483639 value which probably is unexpected.

With checked keyword:

int maxValue = int.MaxValue; //2147483647            
int overflow = checked(maxValue + 10); //OverflowException thrown

With unchecked keyword:

int maxValue = int.MaxValue; //2147483647            
//note the usage of constants
int overflow = unchecked(int.MaxValue + 10); //legal, value is -2147483639

Both declaration styles are correct and equivalent:

int maxValue = int.MaxValue; //2147483647 

int overflow = checked(maxValue + 10);

checked
{
    int overflow = maxValue + 10;
}
int maxValue = int.MaxValue; //2147483647 

int overflow = unchecked(maxValue + 10);

unchecked
{
    int overflow = maxValue + 10;
}

Checking for overflows takes time. In more complex situations of overflow checking, you might want to use the unchecked keyword to improve performance within the checked block like so:

checked
{
    //code to check for overflows
    unchecked
    {
       //code you know it can't overflow so the check can be skipped
    }
}

Unchecks in this case are used to break out from the check blocks to improve performance.

Keep in mind that if performance improvements are not worthy, generally (not just in this situation) it’s usually a bad idea to perform this kind of “optimizations”.

Conclusion

Checking for overflow takes time. In case overflow is a possibility, the checked keyword should be used.

The unchecked keyword should only be used where there is no danger in running into an overflow.

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