skip to content

As a lead, what rule would you set for when a type in a C# codebase may be a struct, and how would you enforce it?

level: principalimportance: should knowfreq 28%

answer

  1. class by default
  2. readonly and valid when zeroed
  3. equality defined explicitly
  4. measure before going large
  5. public API fixes the choice

basics

~20 s

Default to classes; allow a struct for a small, single-value type that is declared readonly, valid when zeroed, defines its equality and is rarely boxed. Require measurements for large or mutable structs, and enforce the rule with analyzers and review.

solid answer

~40 s

I would make class the default and struct the exception that has to meet a short checklist: one logical value, `readonly struct` (or a `readonly record struct`), meaningful when all fields are zero, explicit equality when it is compared or used as a key, and rarely converted to `object` or an interface. Size stays a guideline: around 16 bytes passes without discussion, larger needs a benchmark showing the allocation saving beats the copying. Mutable structs are allowed only in measured hot paths, such as numeric code in a game loop, with the copy traps documented. Enforcement is cheap: IDE0250 and IDE0251 raised in `.editorconfig`, a review question for every new struct, and extra care for public types, because switching a shipped type between struct and class changes its semantics for every caller.

go deeper

for a junior

Know the default: use classes unless a type is a small, immutable single value, and ask before adding a struct.

for a middle

Explain each item of the checklist with the C# behaviour behind it: copies, zeroed defaults and inherited equality.

for a senior

Review new structs against the checklist, request benchmarks for large or mutable ones, and catch missing readonly with IDE0250 and IDE0251.

for a principal

Set the default, the exceptions and the enforcement for the whole codebase, tuned to whether allocation or clarity dominates, and protect public types from later struct/class switches.

## Why a team needs a rule at all The struct versus class choice looks local, but its failure modes surface far from the declaration: a lost write in a loop, a hidden copy through a `readonly` field, an array of zeroed values that break an invariant, a slow dictionary keyed by a struct with a `string` field. None of these produce a compile error unless the type was designed to prevent them. A short rule moves the decision to the one place it is cheap to get right, the moment the type is declared. There is no single right answer. A game client whose frame budget is dominated by allocation will accept more structs than a line-of-business service where clarity matters most. The rule below is a sensible default for most C# codebases, with the dials marked. ## A rule that fits most codebases 1. **Class is the default.** Nobody has to justify a class. 2. **A struct must represent one logical value**: a coordinate, a money amount, a time range. An entity with identity is never a struct. 3. **It must be `readonly struct`** (C# 7.2), or a `readonly record struct` where that fits; the records material covers that choice. This removes lost writes and defensive copies in one keyword. 4. **Its all-zero value must be valid**, because `default`, arrays and fields of containing objects create it without running any constructor. 5. **If it is compared or used as a key, its equality is explicit**: overridden `Equals` and `GetHashCode` plus `IEquatable<T>`, or a record struct. The inherited `ValueType` versions may use reflection and hash only the first field. 6. **Size is a dial, not a wall.** Around 16 bytes, the figure in the design guidelines, passes without discussion; larger needs a benchmark showing the allocation saving beats the copying. ## Exceptions worth allowing - **Hot numeric code.** .NET's own `System.Numerics.Vector3` is a mutable 12-byte struct with public fields, because numeric loops update components in place. Allow this only where profiling shows it matters, and document that every copy site loses writes. - **Interop and layout-sensitive types**, whose shape is dictated by native code. - **Stack-only types**: `ref struct` and spans follow their own rules, covered in the material on low-allocation code, and are outside this rule. ## Enforcing it - Raise **IDE0250** (a struct can be made `readonly`) and **IDE0251** (a member can be made `readonly`) to warnings in `.editorconfig`, so existing structs drift toward immutability. - Add one review question for every new struct: *which rule makes this a struct, and what does its zeroed value mean?* - Require a benchmark in the pull request for any struct larger than the guideline or any mutable struct; how to write one is the material on benchmarks and tracing. - Treat **public types** more strictly. Once a type ships, switching it between struct and class is a breaking change: callers that relied on copies would start sharing one instance, `null` becomes possible or impossible, `default` changes meaning, and compiled callers must be rebuilt. ## The trade-offs a lead weighs | Policy | Gains | Costs | |---|---|---| | Structs anywhere a developer likes | fewer allocations in some paths | lost writes, defensive copies, slow default equality, invalid zeroed values | | Class by default, struct by checklist | predictable semantics; structs where they pay | one review question per struct; occasional benchmark | | No structs except BCL types | simplest mental model | allocation pressure in hot loops; game and numeric code suffers | ## Applying it to the two reviewed types The 3D vector in the game loop passes: one value, 12 bytes, origin as a valid zero, used in large arrays. The team would ask only that it be `readonly` unless profiling justifies in-place updates. The 2 KB sensor-reading struct fails on size, on its zeroed state and on mutation; it goes back to being a class unless a benchmark shows the allocation was the real cost and the code avoids copying it.

  • Why insist on `readonly struct` rather than just advising immutability?
    Advice is invisible to the compiler; `readonly struct` is checked. It forces every field to be `readonly`, makes every member implicitly `readonly`, and so removes both lost writes through copies and the defensive copies the compiler makes on read-only storage. A reviewer then only needs to see the keyword instead of auditing every method.
  • When would you accept a mutable struct?
    In a measured hot path where updating components in place matters, such as vector math in a game loop; `System.Numerics.Vector3` is designed that way. I would require the benchmark, keep the type internal where possible, and document that properties, `foreach` variables and `readonly` fields hand out copies that silently absorb writes.
  • Why treat public structs more strictly than internal ones?
    Because the choice becomes part of the contract. Changing a shipped type from struct to class means callers that copied values now share one instance, a `null` value becomes possible, and `default` stops meaning the zero value; compiled callers must be rebuilt. Internal types can be switched in one change; public ones cannot.

  • Every small type should be a struct because structs avoid the garbage collector.
  • Struct or class is a local choice for each developer and needs no team rule.
  • Switching a public type from struct to class is a safe internal refactoring.
  • The 16-byte guideline is enforced by the compiler, so no review is needed.
  • Readonly structs are slower because every change needs a new value.