As the lead of a C# codebase, would you store money as decimal or as long minor units, and would you turn on CheckForOverflowUnderflow?
answer
- exactness versus size and speed
- fractional rates still need rounding
- default context for the assembly
- code that must wrap on purpose
basics
~20 sMost C# business code should use decimal for money, keeping long minor units for hot paths or storage formats that demand integers. Turning on CheckForOverflowUnderflow, at least in test builds, catches silent integer wrap; deliberate wrapping then needs unchecked.
solid answer
~40 sThere is no single right answer, so the lead should state the trade-off. `decimal` is exact for base-10 amounts, carries its own scale, throws on overflow and keeps code readable; it costs 16 bytes and slower arithmetic. `long` minor units (cents) are 8 bytes and fast, but every amount needs its currency's exponent, every rate (tax, FX, discount) is fractional so multiplication still needs a rounding rule, and overflow wraps silently unless checked. For counters, pick the width first (`long`, or `Int128` since .NET 7 for extreme accumulators). Setting `CheckForOverflowUnderflow` to `true` makes non-constant integral arithmetic throw `OverflowException`; teams enable it everywhere, only in Debug and test builds, or rely on `checked` blocks at boundaries, and wrap hash and checksum code in `unchecked`.
go deeper
Recall the two money representations, decimal amounts and long counts of cents, and that the project property CheckForOverflowUnderflow changes whether int overflow throws.
Explain what each representation costs: decimal's size and speed versus minor units' separate exponent, fractional rates and silent wrap.
Show how each choice fails in production, from a wrapped minor-unit total to a checked build throwing in hashing code, and where tests catch it.
Own the rule: pick the money type and overflow policy for the codebase, justify the trade-off, write it into the standard and make review enforce it.
## The decision a lead owns Two arithmetic rules shape every C# service that handles money or long-running counters: **which type represents money**, and **what happens when integer arithmetic overflows**. Both are cheap to set at the start and expensive to change later, because the choice leaks into database columns, serialization formats, APIs and every calculation. Neither has one right answer; the lead's job is to pick deliberately and enforce it. ## Money: decimal or long minor units | Concern | `decimal` amounts | `long` minor units (cents) | |---|---|---| | Exactness for base-10 amounts | exact up to 28 decimal places | exact, as an integer count | | Size and speed | 16 bytes, arithmetic in software | 8 bytes, native integer arithmetic | | Currency exponent | carried by the value's scale | kept separately (2 for most, 0 or 3 for some) | | Fractional rates (tax, FX, discounts) | multiply directly, then round | need scaled arithmetic or a detour through `decimal` | | Overflow | always throws `OverflowException` | wraps silently unless checked | | Readability in review | `19.99m` reads as money | `1999` needs a convention | **Arguments for `decimal` everywhere**: amounts read naturally, the compiler forces the `m` suffix and blocks implicit mixing with `double`, overflow and division by zero fail loudly, and multiplying by `0.0825m` is direct. Rounding is still needed, but it is one explicit `Math.Round(amount, 2, mode)` in one place. **Arguments for `long` minor units**: half the memory, faster arithmetic in hot loops such as ledgers replayed in bulk or pricing engines, and an integer that every storage engine and wire format can carry without precision questions. The costs are real, though: the currency exponent travels separately, every percentage must be applied with an agreed scaling and rounding rule, and an overflow wraps silently unless the code is checked. A common compromise is `decimal` in the domain model, with a minor-unit `long` only at a boundary that demands it, converted in one tested function. `double` is ruled out for money in both options. ## Counters: choose the width first Overflow policy is a second line of defence; the first is a type wide enough for the quantity. A request counter that can pass two billion belongs in `long`, not `int`. `Int128` (and `UInt128`), added in .NET 7, serve rare cases such as accumulating products of large `long` values; they have no C# keyword or literal suffix, but they support `checked` arithmetic like the built-in integral types. ## Overflow: should the whole assembly be checked? The `CheckForOverflowUnderflow` property sets the default context for every **non-constant** integral expression in the assembly it compiles. Options: 1. **Leave it off (the default)** and use `checked` blocks where an overflow means a bug: amount arithmetic in minor units, size and quota calculations, conversions from wider types. Lowest cost, but it depends on reviewers spotting every place. 2. **Turn it on only for Debug or test builds** with a configuration condition in the project file. Tests and staging fail fast on overflow while production keeps unchecked arithmetic; the risk is that production then behaves differently from the tests on exactly the bug the setting exists to catch. 3. **Turn it on everywhere**. Overflow always fails fast, and production matches tests. The cost is an overflow check on each affected integral operation, usually small but worth measuring on hot loops, and an audit of code that wraps on purpose. Whatever the choice, some code **must** wrap: hash-code mixing, checksums, some random-number generators. Under a checked default each of those needs an explicit `unchecked(...)` or `unchecked { }`. Remember the limits of the setting too: - It changes only the assembly being compiled; referenced packages keep the context they were built with. - `decimal` already throws on overflow, and `double` never does; the setting does not change either. - Constant expressions are checked at compile time regardless. ## A defensible default For a typical line-of-business codebase: - Money in `decimal`, with literals using `m`, one rounding helper with an explicit `MidpointRounding` mode, and minor units only at named boundaries. - Counters and identifiers sized generously, `long` by default. - `CheckForOverflowUnderflow` enabled at least in test builds, with deliberate wrapping marked `unchecked`, and the reasoning written into the team's coding standard so the next reviewer knows which rule applies. A pricing engine or a high-volume ledger may reasonably choose minor units and checked blocks instead; what matters is that the rule is explicit, enforced in review and tested at the edges.
- If a C# project turns on CheckForOverflowUnderflow, what code has to change?Any code that relies on wrapping: hash-code mixing such as `h * 31 + x`, checksums, some random-number generators and bit tricks on signed values. Each needs an explicit `unchecked(...)` or `unchecked { }`, which then wins over the project default. Tests should also cover the boundaries, since a previously silent wrap now throws `OverflowException` at run time.
- Why do long minor units not remove the need for decimal or a rounding rule?Because the rates applied to money are fractional: an 8.25% tax, an exchange rate, a pro-rated discount. Multiplying cents by such a rate yields a fraction of a cent, so the team still needs either `decimal` intermediates or scaled integer arithmetic, plus an explicit rounding mode and a rule for where rounding happens.
- Storing money in cents removes every rounding decision.
- CheckForOverflowUnderflow also makes decimal and double arithmetic throw.
- Turning the setting on also checks code inside referenced NuGet packages.
- Hash-code arithmetic is automatically exempt from a checked default.
- double is acceptable for money if amounts are rounded at display time.
Assumes .NET 10; Int128 and UInt128 have been in the base library since .NET 7, so older targets have no 128-bit integer type.