Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Visual C#
C# Reference
C# Keywords
Statement Types
 checked

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
C# Language Reference
checked (C# Reference)

The checked keyword is used to explicitly enable overflow-checking for integral-type arithmetic operations and conversions.

By default, if an expression produces a value that is outside the range of the destination type, constant expressions cause compile-time errors, and non-constant expressions are evaluated at run-time and raise exceptions. However, the checked keyword can be used to enable checking if it is suppressed globally by compiler options or environment configuration.

See the unchecked examples on using the unchecked keyword.

This sample shows how to use checked for a non-constant expression. The overflow is reported at run-time.

// statements_checked.cs
using System;
class OverFlowTest
{
    static short x = 32767;   // Max short value
    static short y = 32767;

    // Using a checked expression 
    static int CheckedMethod()
    {
        int z = 0;
        try
        {
            z = checked((short)(x + y));
        }
        catch (System.OverflowException e)
        {
            Console.WriteLine(e.ToString());
        }
        return z;
    }

    static void Main()
    {
        Console.WriteLine("Checked output value is: {0}", 
                     CheckedMethod());
    }
}

Sample Output

System.OverflowException: Arithmetic operation resulted in an overflow.
   at OverFlowTest.CheckedMethod()
Checked output value is: 0

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