In C#, why does incrementing an int counter at int.MaxValue wrap silently while int.MaxValue + 1 fails to compile, and what does checked change?
answer
- the default overflow-checking context
- constant expressions are judged differently
- a project property sets the default
- context covers only the code textually inside
basics
~20 sNon-constant integer arithmetic in C# runs unchecked by default, so int.MaxValue + 1 silently wraps. Constant expressions are checked by default, giving CS0220. A checked expression or block throws OverflowException instead; unchecked opts back into wrapping.
solid answer
~40 sC# evaluates non-constant integral arithmetic in an **unchecked** context unless the `CheckForOverflowUnderflow` project property is `true` (it defaults to `false`), so `int.MaxValue + 1` keeps the low 32 bits and becomes `int.MinValue`. Constant expressions are evaluated in a checked context by default, so `int x = int.MaxValue + 1;` fails with CS0220, "The operation overflows at compile time in checked mode". `checked(expr)` or a `checked { }` block makes `++`, `--`, unary `-`, binary `+`, `-`, `*`, `/` and explicit integral conversions throw `OverflowException`; `unchecked` restores wrapping, including for constants. The context covers only code textually inside the block, not methods it calls. `decimal` ignores the context and always throws; `double` and `float` never throw.
code
csharp · 24 linesint requests = int.MaxValue;
requests++; // default context: unchecked
Console.WriteLine(requests); // -2147483648
requests = int.MaxValue;
try
{
checked { requests++; }
}
catch (OverflowException)
{
Console.WriteLine("OverflowException"); // checked block: throws
}
checked
{
Console.WriteLine(Next(int.MaxValue)); // -2147483648: Next's body is not inside the block
}
// int overflowAtCompileTime = int.MaxValue + 1; // CS0220: constant expressions are checked by default
Console.WriteLine(unchecked(int.MaxValue + 1)); // -2147483648: opted out explicitly
static int Next(int value) => value + 1;go deeper
Recall that int arithmetic wraps silently by default, that checked makes it throw OverflowException, and that an overflowing constant expression is a compile error unless marked unchecked.
Explain the three ways to set the context: the checked and unchecked operators, the statement blocks and the CheckForOverflowUnderflow property, and that the context is textual.
Diagnose a counter that went negative in production, choose between a wider type and a checked context, and know which types ignore the context: decimal always throws, double never does.
Weigh turning checked arithmetic on for a whole codebase against checked blocks at boundaries, and plan for code that must wrap on purpose.
## What the overflow-checking context is Every integral operation in C# runs in an **overflow-checking context**, either **checked** or **unchecked**. The context decides what happens when the mathematical result does not fit in the result type: - **Unchecked**: the result is truncated to the low-order bits that fit. For `int`, `int.MaxValue + 1` becomes `int.MinValue` (-2147483648), and `byte b = 255; b++;` leaves `0`. - **Checked**: the runtime throws `System.OverflowException` instead of producing a wrapped value. The context is a property of the **code**, decided when it is compiled, not a property of the value. ## The defaults: run time vs compile time | Kind of expression | Default context | Overflow result | |---|---|---| | Non-constant, `CheckForOverflowUnderflow` unset or `false` | unchecked | silent wrap | | Non-constant, `CheckForOverflowUnderflow` `true` | checked | `OverflowException` | | Constant expression (all operands constants) | checked | compile error CS0220 | A telemetry aggregator that counts requests in an `int` field and runs for weeks therefore never sees an exception when the counter passes 2,147,483,647; the next increment simply produces a large negative number, and dashboards show negative traffic. The same arithmetic written with literals, `int limit = int.MaxValue + 1;`, never reaches run time: the compiler folds the constant, sees the overflow and reports **CS0220**, "The operation overflows at compile time in checked mode". Writing `unchecked(int.MaxValue + 1)` tells the compiler the wrap is intended. ## The checked and unchecked keywords C# offers both an operator form and a statement form: 1. `checked(expression)` and `unchecked(expression)` set the context for one expression. 2. `checked { ... }` and `unchecked { ... }` set it for a block of statements. 3. The `CheckForOverflowUnderflow` project property (`-checked` on the command line) sets the default for every non-constant expression in the assembly being compiled. An explicit keyword always wins over the project default, which is why hashing code commonly wraps its multiply-and-add in `unchecked(...)`: it stays correct even after a team switches the project to checked. ## The context is textual The keywords affect only operations that appear **textually** inside the parentheses or braces. A `checked` block that calls a helper method does not change how the helper's body was compiled; the helper keeps the context of its own source, normally the project default. Only an argument expression written inside the block, such as `Next(big + 1)`, is evaluated as checked. This catches teams who wrap a top-level call in `checked` and assume the whole call tree is now protected. ## Which operations the context affects - The integral arithmetic operators: unary `++`, `--` and `-`, and binary `+`, `-`, `*` and `/`, when the operands are an integral type, `char` or an enum. - Explicit numeric conversions between integral types, and from `float` or `double` to an integral type: `checked((int)someLong)` throws when the value is out of range. - The native-sized `nint` and `nuint` follow the same rules; they are 32-bit or 64-bit depending on the process. - **Not** `decimal`: decimal arithmetic overflow throws `OverflowException` in both contexts, and converting an out-of-range `decimal` to an integral type always throws. - **Not** `double` or `float` arithmetic: it never throws and saturates to positive or negative infinity instead. - Not every exception is about the context: integer division by zero always throws `DivideByZeroException`, and `int.MinValue / -1` throws `OverflowException` even inside `unchecked`. ## Checked conversions and constants Conversions follow the same two-sided rule. At run time, `(int)someLong` with the value `long.MaxValue` keeps the low 32 bits and yields `-1` under the default context, while `checked((int)someLong)` throws `OverflowException`. With a constant operand, the compiler checks the conversion itself: `byte b = (byte)300;` fails with CS0221, "Constant value '300' cannot be converted to a 'byte' (use 'unchecked' syntax to override)", and `unchecked((byte)300)` compiles to `44`. The message itself names the escape hatch, which is a reminder that the compiler treats a constant overflow as a probable mistake rather than an intended wrap. ## Reading the symptom A value that suddenly flips sign or jumps to a tiny number after a long run is the signature of unchecked wrap. The fixes, in rough order of preference, are a wider type for the quantity (`long` for a counter that grows without bound), a `checked` context where an overflow means a bug and should fail fast, and an explicit `unchecked` only where wrapping is the intended arithmetic.
- Does a checked block in C# protect arithmetic inside a method that the block calls?No. `checked` and `unchecked` apply only to operations textually inside the expression or block. A called method keeps the context its own body was compiled with, normally the project default, so `checked { Console.WriteLine(Next(int.MaxValue)); }` still wraps inside `Next`. Only expressions written in the block, including argument expressions such as `Next(x + 1)`, are evaluated as checked.
- If a project sets CheckForOverflowUnderflow to true, can a C# method still wrap on purpose?Yes. The property only changes the default context for non-constant expressions in that assembly. An explicit `unchecked(...)` expression or `unchecked { }` block still wins, which is how hash-code mixing, checksums and other deliberately wrapping arithmetic stay correct when the rest of the project is checked.
- Which C# numeric types ignore the checked or unchecked context entirely?`decimal` and the floating-point types. Decimal arithmetic that overflows throws `OverflowException` in both contexts, and a `decimal` converted to an out-of-range integral type always throws. `float` and `double` arithmetic never throws; it saturates to infinity or produces NaN. The context matters for a `double` only when it is explicitly converted to an integral type.
- C# throws OverflowException on int overflow by default.
- A checked block also protects every method called from inside it.
- int.MaxValue + 1 written with constants compiles and wraps at run time.
- unchecked makes decimal arithmetic wrap instead of throwing.
- Overflowing a double inside checked throws OverflowException.