Share via


checked (C# Reference) 

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

Remarks

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.

Example

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

C# Language Specification

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

See Also

Reference

C# Keywords
Checked and Unchecked (C# Reference)
unchecked (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference