Export (0) Print
Expand All

unchecked (C# Reference)

The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.

In an unchecked context, if an expression produces a value that is outside the range of the destination type, the result is truncated. For example:


        unchecked
{
    int val = 2147483647 * 2;
}

Because the calculation above is performed in an unchecked block, the fact that the result is too large for an integer is ignored, and val is assigned the value -2. By default, overflow detection is enabled, which has the same effect as using checked.

In the example above, had unchecked been omitted, a compilation error would occur because the expression uses constants and the result is known at compile time. The unchecked keyword also suppresses overflow detection for non-constant expressions, which otherwise result in OverflowException at runtime.

The unchecked keyword can also be used as an operator, like this:

public int UncheckedAdd(int a, int b)
{
    return unchecked(a + b);
}

This sample shows how to use the unchecked statement, using unchecked with constant expressions.

// statements_unchecked.cs
using System;

class TestClass 
{
    const int x = 2147483647;   // Max int 
    const int y = 2;

    static void Main() 
    {
        int z;
        unchecked 
        {
            z = x * y;
        }
        Console.WriteLine("Unchecked output value: {0}", z);
    }
}

Output

 
Unchecked output value: -2

For more information, see the following sections in the C# Language Specification:

  • 5.3.3.2 Block statements, checked, and unchecked statements

  • 7.5.12 The checked and unchecked operators

  • 8.11 The checked and unchecked statements

Community Additions

ADD
Show:
© 2014 Microsoft