Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Visual C#
C# Reference
C# Keywords
Statement Types
 unchecked
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
C# Language Reference
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

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker