skip to content

In a C# generic Add<T> where T : IAdditionOperators<T, T, T>, why does checked(a + b) throw for int.MaxValue but wrap for a struct defining only operator +?

level: seniorimportance: nice to knowfreq 15%

answer

  1. two operators behind one +
  2. the context picks which one
  3. a static virtual default body
  4. checked does not flow into calls
  5. operator checked + since C# 11

basics

~20 s

In a checked context the compiler calls the checked operator +, a static virtual member of IAdditionOperators. int implements it with overflow-checked addition and throws OverflowException; a struct that defines only operator + gets the default body, which calls that unchecked operator and wraps.

solid answer

~50 s

Since C# 11 a type can declare two versions of an operator, `operator +` and `operator checked +`, and the compiler picks the checked one inside a `checked` expression or block. `IAdditionOperators<TSelf, TOther, TResult>` declares the regular operator as `static abstract` and the checked one as `static virtual` with the default body `=> left + right`. So `checked(a + b)` in generic code calls `T`'s checked operator: `int` implements it as `checked(left + right)` and throws `OverflowException`, while a `Counter` struct that wrote only `operator +` falls back to the default, which calls its unchecked `+`, and the sum wraps to -2147483648. The `checked` keyword selects which operator is called; it does not change the context inside that operator's body. The fix is to declare `operator checked +` on `Counter` with checked arithmetic, alongside the regular operator, which C# requires (CS9025).

code

csharp · 24 lines
csharp
using System.Numerics;

Try("int", () => Add(int.MaxValue, 1));
Try("Counter", () => Add(new Counter(int.MaxValue), new Counter(1)).Value);
Try("SafeCounter", () => Add(new SafeCounter(int.MaxValue), new SafeCounter(1)).Value);

static T Add<T>(T a, T b) where T : IAdditionOperators<T, T, T> => checked(a + b);

static void Try(string name, Func<int> f)
{
    try { Console.WriteLine($"{name}: {f()}"); }
    catch (OverflowException) { Console.WriteLine($"{name}: OverflowException"); }
}

readonly record struct Counter(int Value) : IAdditionOperators<Counter, Counter, Counter>
{
    public static Counter operator +(Counter l, Counter r) => new(l.Value + r.Value);
}

readonly record struct SafeCounter(int Value) : IAdditionOperators<SafeCounter, SafeCounter, SafeCounter>
{
    public static SafeCounter operator +(SafeCounter l, SafeCounter r) => new(unchecked(l.Value + r.Value));
    public static SafeCounter operator checked +(SafeCounter l, SafeCounter r) => new(checked(l.Value + r.Value));
}

go deeper

for a junior

Recall that checked makes built-in integer overflow throw OverflowException, and that a user-defined type decides its own overflow behaviour.

for a middle

Explain that C# 11 lets a type declare both operator + and operator checked +, and that the context around the expression picks which one is called.

for a senior

Trace why a struct without a checked operator wraps in generic code, why checked is lexical, and how to fix the type without breaking callers.

for a principal

Decide whether the team's numeric types must implement checked operators and whether generic library code may rely on checked to catch overflow.

## Two operators behind one `+` C# has always had `checked` and `unchecked` contexts for the built-in integer types: inside `checked(...)` an `int` addition that overflows throws `OverflowException`, and outside it the result wraps. Before **C# 11** that choice did not exist for user-defined operators; a type had one `operator +`, and it behaved the same in both contexts. C# 11 added **checked user-defined operators**: - `public static T operator +(T left, T right)` is used in an unchecked context. - `public static T operator checked +(T left, T right)` is used in a checked context. Overload resolution looks first for operators matching the current context and falls back to the other kind when none exists. Inside the body of a checked operator the context is the default one, not checked, so the body must write `checked(...)` itself. ## What IAdditionOperators declares The .NET source declares both forms, and they are not equally required: ```csharp static abstract TResult operator +(TSelf left, TOther right); static virtual TResult operator checked +(TSelf left, TOther right) => left + right; ``` The checked operator is **static virtual** with a default body that simply calls the regular operator. The same pairing appears in `ISubtractionOperators`, `IMultiplyOperators`, `IDivisionOperators`, `IIncrementOperators`, `IDecrementOperators` and `IUnaryNegationOperators`. Built-in types override the default: `int` implements its checked `+` as `checked(left + right)`. ## Tracing Add<T> ```csharp static T Add<T>(T a, T b) where T : IAdditionOperators<T, T, T> => checked(a + b); ``` Because the expression is inside `checked`, the compiler binds `a + b` to `T`'s checked operator. At run time that resolves to whatever the type argument supplies: | Type argument | Checked operator that runs | `Add(MaxValue, 1)` | |---|---|---| | `int` | `int`'s own, `checked(left + right)` | `OverflowException` | | `Counter` with only `operator +` | the interface default, which calls `Counter`'s `+` | wraps to -2147483648 | | `SafeCounter` with both operators | `SafeCounter`'s `operator checked +` | `OverflowException` | ## Why the default wraps Two rules combine: 1. The default `operator checked +` just calls `left + right`, the type's unchecked operator. 2. `checked` is **lexical**: it governs only the operators written inside its parentheses or block. It does not flow into the methods those operators call, so `Counter`'s `+` body runs in whatever context that body was compiled in, which by default is unchecked. For the same reason, wrapping a call site in `checked(Add(...))` does nothing to the additions inside a generic method whose body says plain `a + b`; that call still returns -2147483648 for `int`. The context that matters is the one around the operator expression itself, set by the `checked` keyword there or by the project's `CheckForOverflowUnderflow` setting. ## The same rule outside generics Nothing here is special to generic code. In ordinary code, `checked(a + new Counter(1))` on a `Counter` that declares only `operator +` finds no checked operator, falls back to the regular one, and also prints -2147483648. Generic code only makes the fallback harder to see, because the call site says `a + b` on a `T` and gives no hint which types implement the checked form. The `CheckForOverflowUnderflow` project setting changes the default context for every expression compiled in that project, including the bodies of its own operators, but it has no effect on operators compiled in another assembly. ## Fixing your own types - Declare `public static Counter operator checked +(Counter l, Counter r) => new(checked(l.Value + r.Value));` next to the regular operator. - Keep the regular operator: declaring only the checked one fails with **CS9025**, "requires a matching non-checked version of the operator to also be defined". - Write `checked(...)` inside the checked operator explicitly, because its body does not inherit a checked context. - If wrapping is the documented behaviour of the type, say so; if overflow can never happen, the default is harmless. - Apply the same review to `-`, `*`, `/`, `++`, `--` and unary `-`, which have checked forms in their interfaces too. ## What a reviewer should ask - Does this generic code rely on `checked` to catch overflow? Then every type that can flow into it needs real checked operators. - Do our own numeric structs implement the checked forms of the operator interfaces they declare, or do they quietly inherit the wrapping default?

  • Does wrapping the call checked(AddPlain(int.MaxValue, 1)) make the generic method's addition checked?
    No. `checked` is lexical: it applies only to operator expressions written inside it, not to code in methods it calls. If `AddPlain<T>` returns `a + b` without `checked`, the call returns -2147483648 for `int`. Put `checked` around the expression inside the generic method, or turn on `CheckForOverflowUnderflow` for that project.
  • Why can't Counter declare only operator checked +?
    C# requires a checked operator to have a matching regular operator; declaring only the checked form fails with CS9025, "requires a matching non-checked version of the operator to also be defined". With `IAdditionOperators`, the regular `+` is static abstract anyway, so leaving it out also reports CS0535.
  • Which generic-math operator interfaces carry a checked form?
    In .NET 10, `IAdditionOperators`, `ISubtractionOperators`, `IMultiplyOperators`, `IDivisionOperators`, `IIncrementOperators`, `IDecrementOperators` and `IUnaryNegationOperators` each declare a static virtual checked operator whose default body calls the regular one. A custom numeric type should implement each checked form whose overflow it wants reported.

  • Wrapping checked around a call to a generic method checks the additions inside it.
  • A checked context makes every user-defined operator throw on overflow automatically.
  • Declaring only operator checked + is enough; the compiler supplies the regular one.
  • Every type implementing IAdditionOperators must write its own operator checked +.
  • The body of a checked operator automatically runs in a checked context.