C# › Indexers & Operator Overloading
How do you implement the 'checked' operator overload variant (introduced in C# 11) to provide overflow-checking behavior for a custom numeric type?
AdvancedAnswer
C# 11 lets you define a SEPARATE overload of an operator specifically for 'checked' contexts (using 'checked operator +' syntax) alongside the normal unchecked version — the compiler automatically calls the checked variant when the surrounding code is in a 'checked' block/expression, letting custom numeric types participate correctly in C#'s overflow-checking semantics.
public struct SafeInt {
public int Value;
public static SafeInt operator +(SafeInt a, SafeInt b) => new SafeInt { Value = a.Value + b.Value }; // unchecked
public static SafeInt operator checked +(SafeInt a, SafeInt b) =>
new SafeInt { Value = checked(a.Value + b.Value) }; // throws OverflowException if it overflows
}Real-world example Building a custom numeric type that correctly respects C#'s checked/unchecked overflow-detection context, matching built-in numeric type behavior.