In C#, why does `price.Amount = 0m;` compile for `record struct Price(decimal Amount, string Currency)` but fail for a `readonly record struct`?
answer
- which accessor is generated
- set versus init
- the readonly modifier changes it
- init-only assignment diagnostic
basics
~20 sA positional C# record struct generates get and set properties, so they are mutable; a readonly record struct generates get and init, so assigning one after construction is error CS8852, and a with expression makes a changed copy.
solid answer
~50 sThe accessor the compiler writes for a positional parameter depends on the declaration. A `record class` and a `readonly record struct` get `{ get; init; }` properties; a plain `record struct` gets `{ get; set; }`. So with `record struct Price(...)`, any code holding a variable of that type — a local, a field, an array element — can write `price.Amount = 0m`, and in an array that write lands in the stored element. Declaring `readonly record struct Price(...)` turns the same line into error CS8852, because `Amount` is now init-only. `readonly` also makes the compiler require every instance field and auto-property to be read-only (CS8341 otherwise). To change a readonly record struct you write `price with { Amount = 0m }`, which copies the value and sets `Amount` on the copy. If one property must stay mutable, keep `record struct` and redeclare the others as `{ get; init; }`.
code
csharp · 14 linesusing System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var ladder = new[] { new Price(101.25m, "USD"), new Price(101.50m, "USD") };
ladder[0].Amount = 0m; // compiles: the positional property has a public set
Console.WriteLine(ladder[0]);
var lots = new Quantity(5);
// lots.Lots = 6; // error CS8852: Lots is init-only
var more = lots with { Lots = 6 }; // a changed copy instead
Console.WriteLine($"{lots} -> {more}");
record struct Price(decimal Amount, string Currency);
readonly record struct Quantity(int Lots);go deeper
Remember that a positional record struct gets get and set, while readonly record struct and record class get get and init.
Explain the CS8852 error, how with copies a readonly record struct, and why an array element or field can be written in place while the value is still copied on assignment.
Show how a mutable record struct lets a helper change shared state by mistake, and why readonly record struct should be the team default for value types.
Treat readonly record struct as the house style for small values, keep plain record struct for deliberate in-place accumulators, and state the rule in review guidance.
## Two spellings, two accessor sets Since C# 10, a record can be a class or a struct, and a struct record can carry the `readonly` modifier. For every parameter in the parameter list, the compiler generates a public auto-property with the same name and type, initialized from the parameter. **Which accessors** it writes is the whole difference: | Declaration | Generated positional property | Assignable after construction? | |---|---|---| | `record class Price(decimal Amount, ...)` | `public decimal Amount { get; init; }` | no | | `readonly record struct Price(decimal Amount, ...)` | `public decimal Amount { get; init; }` | no | | `record struct Price(decimal Amount, ...)` | `public decimal Amount { get; set; }` | **yes** | The asymmetry surprises people who learned records as "immutable data". A plain `record struct` was designed to behave like an ordinary struct with value equality added, and structs are mutable unless declared `readonly`. ## How the trading bug happens Take a trading app that turned its `Price` and `Quantity` record classes into record structs to stop allocating on every tick. `Price` was written as `record struct Price(decimal Amount, string Currency)`. 1. An order book stores a price ladder as `Price[]`. 2. A rounding helper, meant to work on a local copy, is refactored to take the ladder and an index. 3. It writes `ladder[i].Amount = Math.Round(ladder[i].Amount, 2);` — an array element is a variable, so the setter runs on the stored element itself. 4. Nothing fails to compile, and every reader of the ladder now sees the rounded price. With `readonly record struct Price(...)`, step 3 is error CS8852: > Init-only property or indexer 'Price.Amount' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. The only way to "change" the value is then to build a new one and store it deliberately: `ladder[i] = ladder[i] with { Amount = rounded };`. ## What `readonly` adds beyond `init` `readonly record struct` is a `readonly struct` that is also a record, so the struct rules apply: - every instance field must be `readonly`; - every auto-property you add must be get-only or `init`: `public string Desk { get; set; }` in a `readonly record struct` is error CS8341, "Auto-implemented instance properties in readonly structs must be readonly"; - every instance member other than a constructor is implicitly `readonly`, so the compiler knows no member call can modify the value. A plain `record struct` lets you choose per member. You can keep the type mutable and still freeze one positional property by declaring it yourself, which replaces the generated one: ```csharp record struct Price(decimal Amount, string Currency) { public decimal Amount { get; init; } = Amount; } ``` ## Immutability is shallow `init` stops the **property** from being reassigned. If a member holds a reference — a `List<Fill>` or an array — the object it refers to can still be changed through that reference. A `readonly record struct` holding a list is a value whose list is shared by every copy. ## Where a mutable record struct can and cannot be written Copying still applies to a mutable `record struct`, which decides whether a write sticks: - a **local**, a **field** of a class, or an **array element** is a variable, so `x.Amount = 0m` changes the value stored there; - a value read through a **property getter** or a `List<T>` indexer is a temporary copy, and the compiler rejects the write with CS1612; - a value passed to a method **by value** is that method's own copy, so a write inside the method is invisible to the caller. The first row is where accidental mutation does damage, because the write lands in shared storage without any warning. ## Which one to pick - **`readonly record struct`** for values that represent one thing — a price, a quantity, a coordinate. It is the default choice: mutations become compile errors and `with` makes changes explicit. - **`record struct`** when the value is a small mutable bag that code updates in place on purpose, such as an accumulator inside one method, and you still want value equality and `ToString`. - If you find yourself writing `{ get; init; }` for every positional property of a `record struct`, you wanted `readonly record struct`. ## Version note Record structs, `readonly record struct` and `with` on any struct all arrived in C# 10, so every supported .NET release has them; nothing here changed in C# 13 or C# 14.
- If a mutable C# record struct is a Dictionary key, can mutating it corrupt the dictionary?Not through the dictionary's public API. `Add` stores its own copy of the key, and the `Keys` collection hands out copies, so a later `key.Amount = 0m` changes only your local variable. The lookup then misses because your variable is now a different value. The real hazard is confusion, not a broken hash table.
- Can a `readonly record struct` keep one positional property settable?No. In a readonly struct every auto-property must be read-only, and declaring `{ get; set; }` is error CS8341. If one property must be settable, declare a plain `record struct` and make the other properties `{ get; init; }` by redeclaring them.
- Positional properties are init-only in every kind of record.
- readonly record struct also makes a referenced list immutable.
- Setting a record struct property changes every copy that was made earlier.
- A with expression on a record struct calls a generated Clone method.