🔧 C#: Fix a Ref Readonly Parameter Silently Copying on Call
C# 12’s ref readonly parameters are meant to pass a large struct by reference without letting the callee mutate it, but they only avoid a copy when the caller passes a value with a stable storage location — a variable. Passing the result of a method call or a property instead gives the compiler nothing stable to reference, so it silently creates a temporary copy to satisfy the parameter anyway, fully legal and uncomplained-about by default, which defeats the entire performance purpose of using ref readonly in the first place.
🔎 The Problem
void Transform(ref readonly Matrix4x4Big m) { /* ... */ }
Transform(GetMatrix()); // GetMatrix() returns a struct by value -
// compiler creates a temp copy to pass by ref,
// the copy ref readonly was meant to avoid
var m = GetMatrix();
Transform(in m); // no copy - m is a real variable
✅ Fix: Pass an Actual Variable, and Turn On the Warning That Catches This
- Enable the compiler warning that flags a
ref readonlyargument that isn’t a variable, so the compiler surfaces the silent copy instead of staying quiet about it. - Store a method or property result in a local variable first, then pass that variable by
ref readonly, whenever the call site is a hot path where the whole point of the parameter was avoiding a struct copy. - Benchmark the specific call site before assuming
ref readonlybought anything — if every call site actually passes an expression rather than a variable, the parameter is providing mutation safety but none of the copy-avoidance performance it was added for.
🚨 Why This Is Dangerous
- A hot-path struct still being copied on every call despite being passed
ref readonlycan mean a performance optimization silently did nothing, and without the specific compiler warning enabled, nothing in a normal build will tell you that.
ref readonly promises not to mutate your struct — it never promised not to copy it, if that’s the only way the call site gave it to work with.



