In C#, why can calling a method on a large struct held in a readonly field or received as an in parameter copy the whole struct on every call?
answer
- read-only storage must stay unchanged
- a method may write to this
- a hidden temporary per call
- readonly struct or readonly members
- CS8656 inside readonly members
basics
~20 sA readonly field or in parameter must not change, but a struct member not marked readonly may write to this, so the compiler runs it on a hidden copy. Declaring the struct or its members readonly removes the copy.
solid answer
~50 sWhen the target of a call is read-only storage, such as a `readonly` field outside a constructor or an `in` parameter, and the member is not known to leave the struct unchanged, C# copies the value into a temporary and calls the member on that. The storage stays intact, but each call pays a full copy, 2 KB per call for a 2 KB sensor-reading struct, and any write the method makes is silently thrown away. No warning appears at those call sites. Declaring the type `readonly struct` (C# 7.2) or marking members `readonly` (C# 8) tells the compiler a member cannot modify `this`, so it calls the member on the storage directly. Reading a field never copies, and auto-property getters are implicitly `readonly`; the IDE0250 and IDE0251 suggestions point out where the modifier fits.
code
csharp · 23 linesvar station = new Station();
station.Recalibrate();
station.Recalibrate();
Console.WriteLine($"readonly field: {station.Offset}"); // 0
var reading = new SensorReading();
Adjust(in reading);
Console.WriteLine($"in parameter: {reading.Offset}"); // 0
static void Adjust(in SensorReading r) => r.Calibrate();
struct SensorReading
{
public double Offset;
public void Calibrate() => Offset += 0.5; // not readonly: may write this
}
class Station
{
private readonly SensorReading _last;
public void Recalibrate() => _last.Calibrate(); // runs on a hidden copy
public double Offset => _last.Offset; // a field read: no copy
}go deeper
Know that a struct method called through a readonly field may run on a copy, so changes it makes can vanish.
Explain which accesses copy (non-readonly members on read-only storage) and which do not (field reads, auto-property getters, readonly members).
Diagnose lost writes and copying costs on large structs passed by in or stored in readonly fields, and fix the type with readonly struct or readonly members.
Decide whether structs in hot paths must be readonly by rule, enforced through IDE0250 and IDE0251, rather than relying on reviewers to spot hidden copies.
## The rule the compiler is protecting A struct member that is not marked `readonly` may assign the struct's fields through `this`. When such a member is called on **read-only storage**, the compiler cannot let it write there, so it copies the value into a hidden temporary and calls the member on the temporary. That temporary is a **defensive copy**. The storage keeps its value, which is the point, but the copy costs time and any write the member made disappears with it. Read-only storage includes: - a `readonly` field, read anywhere except inside a constructor of its own type; - an `in` parameter (the passing rules themselves are the lesson on by-reference parameters); - a `ref readonly` local or a value returned by `ref readonly`; - `this` inside a `readonly` member, when that member calls a non-`readonly` one. ## Which accesses copy and which do not | Access on read-only storage | Mutable struct | `readonly struct` | |---|---|---| | Read a field, e.g. `_last.Offset` | no copy | no copy | | Call an auto-property getter | no copy; the getter is implicitly `readonly` | no copy | | Call a method or a property body not marked `readonly` | **copy on every call** | cannot occur: every member is implicitly `readonly` | | Call a member marked `readonly` | no copy | no copy | The compiler reports nothing at the call sites in the third row. The warning it does have for defensive copies is **CS8656**, raised inside a `readonly` member that calls a non-`readonly` member: "Call to non-readonly member '...' from a 'readonly' member results in an implicit copy of 'this'." ## A worked example The program below runs on .NET 10. `Calibrate` is an ordinary, non-`readonly` method that adds 0.5 to a field. Called through a `readonly` field, and again through an `in` parameter, it runs on a temporary copy each time, so both prints show 0. ```csharp var station = new Station(); station.Recalibrate(); Console.WriteLine(station.Offset); // 0 struct SensorReading { public double Offset; public void Calibrate() => Offset += 0.5; } class Station { private readonly SensorReading _last; public void Recalibrate() => _last.Calibrate(); // hidden copy public double Offset => _last.Offset; // field read, no copy } ``` ## Why it matters for a large struct The copy is the size of the struct. For a 12-byte vector it is a few instructions; for the 2 KB sensor-reading struct in this scenario, each method call through a `readonly` field copies 2 KB before doing any work. The `in` modifier makes the trap worse: a teammate adds `in` to avoid copying the argument, and then every non-`readonly` member called inside the method copies it anyway. With a mutable struct, `in` can end up making more copies than passing by value would. ## How to remove the copies 1. **Declare the type `readonly struct`** (C# 7.2). Every field must be `readonly` and every property get-only or init-only, and every member except constructors becomes implicitly `readonly`. The compiler then calls members directly on the storage. 2. **Mark individual members `readonly`** (C# 8) when the struct must keep some mutating members. A `readonly` method or property may not assign fields, and the compiler trusts it not to change `this`. 3. **Watch CS8656.** A `readonly` member that calls a non-`readonly` one brings the copy back, this time with a warning. 4. **Let the IDE help.** IDE0250 suggests making a struct `readonly` when all of its members already are; IDE0251 suggests marking an individual member `readonly`. 5. **Question the struct.** A 2 KB value that is mutated through method calls is rarely a good struct; a class avoids the copying entirely. ## Points that are easy to overstate - The copy is made only for members **not** known to be `readonly`; reading a field or calling an auto-property getter is free. - The copy keeps the storage intact; it is not a compiler bug, and fixing it means changing the type, not the call. - The `readonly` modifier on a struct does not freeze objects it references: a `List<T>` field cannot be replaced, but items can still be added to it.
- Does reading a property of a mutable struct through a readonly field always copy it?No. An auto-implemented property's `get` accessor is implicitly `readonly`, so calling it needs no copy. A property whose getter has a body and lacks the `readonly` modifier is treated like any non-`readonly` method, and calling it on read-only storage copies the struct. Reading a field directly never copies.
- When does the compiler warn about a defensive copy?Its warning for this is CS8656, raised inside a `readonly` member that calls a non-`readonly` member and so copies `this`. Copies made for calls through a `readonly` field or an `in` parameter produce no diagnostic, which is why IDE0250 and IDE0251 suggestions, or simply declaring structs `readonly`, are the practical defences.
- Can a `readonly struct` still have its state changed by one of its own members?Not its own fields: they are all `readonly`, and no member except a constructor can assign them. A field that references a mutable object is another matter; the reference cannot be replaced, but the object it points to, such as a `List<T>`, can still be changed through it.
Lending an original document to someone who might write on it: you photocopy it and hand over the copy, their notes land on the photocopy, and a thick binder costs a full photocopy every time. A document stamped read-only can be handed over as it is.
- Passing a struct as an in parameter always avoids copying it.
- The compiler warns whenever it makes a defensive copy.
- A readonly field stops only reassignment, so method calls mutate the struct in place.
- Reading a field of a struct in a readonly field copies the whole struct.
- Marking a struct readonly makes the objects its fields reference immutable too.