Codectionary / Developer documentation / C#

Checked Integer Overflow

checked makes overflowing integral arithmetic throw OverflowException. Its effect applies to operations textually inside the checked context, not automatically to code called from it. Use a .NET 8+ console project; replace Program.cs with this C# example.

Read the syntax

checked makes overflowing integral arithmetic throw OverflowException. Its effect applies to operations textually inside the checked context, not automatically to code called from it. Use a .NET 8+ console project; replace Program.cs with this C# example.

The runtime value cannot fit in Int32 after incrementing, so evaluation throws before assigning result.

Syntax

checked { int result = value + 1; }

Examples

Checked Integer Overflow

Use a .NET 8+ console project; replace Program.cs with this C# example.

using System;
int value = int.MaxValue;
try
{
    int result = checked(value + 1);
    Console.WriteLine(result);
}
catch (OverflowException)
{
    Console.WriteLine("overflow rejected");
}
  1. Expected output: overflow rejected
  2. The runtime value cannot fit in Int32 after incrementing, so evaluation throws before assigning result.
  3. Use checked at boundaries where overflow must not wrap silently.

Best practices

  • Use checked at boundaries where overflow must not wrap silently.
  • Choose a wider or arbitrary-precision type when large results are legitimate.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading