skip to content

A C# trading app changes `Price` from a `record class` to a `readonly record struct` to cut allocations; what behaviour changes for code that uses it?

level: seniorimportance: should knowfreq 30%

answer

  1. value, not reference
  2. constructors that never run
  3. null checks that go quiet
  4. no base type, no EqualityContract
  5. boxing and copy size

basics

~20 s

Price becomes a copied, never-null value: default(Price), new Price() and new arrays skip constructor validation, price == null is always false, inheritance is gone, and object or interface use boxes it. Field-wise value equality is unchanged.

solid answer

~50 s

Equality is the one thing that stays: both kinds compare field by field. Everything about identity and construction changes. Assignment and argument passing now copy the 24-byte value. `default(Price)`, `new Price()` and every element of `new Price[n]` are zero-filled without running the primary constructor, so `Currency` can be null despite its validation. A `Price` can no longer be null: `Price p = null` is CS0037, and an existing `price == null` check compiles with warning CS8073 and is always false — use `Price?` (that is `Nullable<Price>`) where absence is real. A record struct cannot be a base type and has no `EqualityContract`, so any derived price record must go. Converting to `object` or an interface boxes, which allocates again. The allocation win is real in arrays, fields and `HashSet<Price>`, where `IEquatable<Price>` avoids boxing on lookup.

code

csharp · 20 lines
csharp
var viaNew = new Price();                 // no primary constructor runs
Price viaDefault = default;
var book = new Price[3];                  // every element is default(Price)
Console.WriteLine(viaNew == viaDefault && viaDefault == book[2]);
Console.WriteLine(book[0].Currency is null);   // the null check never ran

try { _ = new Price(-1m, "USD"); }
catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.ParamName); }

// Price none = null;                     // error CS0037
Price? maybe = null;                      // Nullable<Price>, a different type
Console.WriteLine(maybe.HasValue);

readonly record struct Price(decimal Amount, string Currency)
{
    public decimal Amount { get; init; } =
        Amount >= 0 ? Amount : throw new ArgumentOutOfRangeException(nameof(Amount));
    public string Currency { get; init; } =
        Currency ?? throw new ArgumentNullException(nameof(Currency));
}

go deeper

for a junior

Know that a record struct is a value type: it is copied on assignment and cannot be null, while a record class is a reference type.

for a middle

Explain how default, new Price() and arrays create instances without the primary constructor, and why the struct version cannot have a base type.

for a senior

Walk the migration: find the null checks CS8073 flags, the validation default bypasses, the derived records, and the boxing sites that cancel the allocation win.

for a principal

Weigh allocation savings against lost invariants and nullability, and require a measurement before changing a widely used type from record class to record struct.

## What stays the same The **equality definition** is the same for a record class and a record struct: two instances are equal when they have the same type and every field compares equal through `EqualityComparer<T>.Default`. `==`, `!=`, `ToString`, `Deconstruct` and `with` expressions all keep working at the source level. That is why the change looks safe in a diff. The behaviour around it is not the same. ## What changes, row by row | Concern | `record class Price` | `readonly record struct Price` | |---|---|---| | storage | heap object; variables hold references | value stored inline in the variable, field or array slot | | assignment and arguments | copy a reference | copy the whole value (24 bytes on 64-bit: a `decimal` plus a string reference) | | `null` | a valid value | impossible; `Price?` is `Nullable<Price>`, a different type | | `default` and `new Price[n]` | null references | zero-filled values; no constructor ran | | inheritance | can be a base record; `EqualityContract` compares run-time types | implicitly sealed; no `EqualityContract` | | `with` | calls the synthesized clone method and copy constructor | copies the value, then sets the listed members | | `object` or interface use | no extra allocation | **boxes**: a new heap object per conversion | | reference identity | `ReferenceEquals` meaningful | none; every box is a distinct object | ## Construction paths that skip validation A record class can enforce "Currency is never null" in its primary constructor, because every instance goes through a constructor. A struct cannot. These paths produce a `Price` without running the primary constructor: 1. `default(Price)` and the `default` literal; 2. `new Price()` — for a positional record struct without a declared parameterless constructor, the implicit one zero-fills every field; 3. every element of a new array, `new Price[3]`; 4. a field of type `Price` in a class before anything assigns it. Since C# 10 you can declare `public Price() : this(0m, "USD") { }`, and then `new Price()` runs it — but `default(Price)` and array elements still do not. Code downstream of these paths must expect `Amount = 0` and `Currency = null`. ## Null checks that go quiet Existing code written for the class version often checks for null: - `if (price == null)` still compiles, because the compiler lifts `==` to `Price?`; it reports warning **CS8073**, "The result of the expression is always 'false'", and the branch is dead; - `if (price is null)` stops compiling: error **CS0037**, "Cannot convert null to 'Price' because it is a non-nullable value type"; - a method that returned `null` for "no price" must now return `Price?` or use a `TryGet` pattern. Treat CS8073 as an error during such a migration; it marks every place where the absence of a price was being handled. ## Inheritance disappears A record struct cannot derive from another record or struct and cannot be a base type: `abstract` and `sealed` are not valid modifiers on it (CS0106), and listing a record struct in a base list fails because only interfaces may appear there. A `PremiumPrice : Price` record has to become composition or a separate type. With no hierarchy there is no `EqualityContract` and no virtual `PrintMembers`. ## Where the allocation win is real, and where it is not - **Arrays, `List<Price>`, fields**: values are stored inline, so a million prices are one array, not a million objects. - **Hash-based collections**: a record struct implements `IEquatable<Price>`, so `EqualityComparer<Price>.Default` is the generic comparer and lookups do not box. A plain struct with the same fields gets the object comparer, which boxes and, because of the string field, falls back to reflection in `ValueType.Equals`; the second snippet measures 0 bytes against about 256 bytes per lookup. - **Boxing**: storing a `Price` in an `object`, a non-generic collection, or a variable typed as an interface allocates a box every time. A hot path that does this loses the win. - **Copy cost**: Microsoft's design guidelines suggest a struct have an instance size under 16 bytes. This `Price` is 24 bytes, so passing it around copies more than a reference; it is still usually cheaper than an allocation, but measure. ## Choosing among the three | Need | Pick | |---|---| | small immutable value, value equality, heavy use in collections | `readonly record struct` | | an invariant every instance must satisfy, null as "absent", or a hierarchy | `record class` | | a value type with hand-tuned layout or equality written by hand | plain `struct` with `IEquatable<T>` |

  • Why does a HashSet of a plain struct allocate on every lookup when a record struct does not?
    For a struct like this, `EqualityComparer<T>.Default` uses the generic comparer when `T` implements `IEquatable<T>` and the object comparer otherwise. A record struct does, so `Contains` calls `Equals(Price)` directly. A plain struct gets the object comparer, which calls `Equals(object)` and boxes the value; `ValueType.Equals` then reads fields by reflection when the struct holds a reference such as a string. One run on .NET 10 measured about 256 bytes per lookup.
  • After the switch, what does an old `if (price == null)` check do?
    It still compiles: the compiler lifts the synthesized `==` to `Price?` and compares against a null `Price?`. Because a non-nullable `Price` is never null, it reports warning CS8073, "The result of the expression is always 'false'", and the branch never runs. `price is null` is error CS0037. Where absence is real, change the type to `Price?`.

  • A readonly record struct guarantees its primary constructor ran for every instance.
  • A record struct can derive from another record struct to share members.
  • Switching to a struct removes allocations even when the value is stored as object.
  • Existing price == null checks keep catching missing prices after the switch.
  • Moving to a struct changes Price equality from field-wise to reference equality.