skip to content

In C#, how does a method returning ref to a sensor array's largest element let callers update it, and what may it never return?

level: middleimportance: should knowfreq 35%

answer

  1. an alias, not a copy
  2. ref at both ends
  3. storage must outlive the call
  4. ref readonly for read-only access
  5. CS8168 and CS8166

basics

~20 s

A ref return hands back an alias to existing storage; a caller who keeps it in a ref local writes straight into the array. Only storage that outlives the call may be returned, never a local (CS8168) or a by-value parameter (CS8166).

solid answer

~50 s

`static ref double Largest(double[] values)` ends with `return ref values[best];`, which returns a reference to the array slot rather than its value. The caller writes `ref double peak = ref Largest(readings);` and `peak = 40.0;` changes `readings[best]`. Both `ref`s matter: `double copy = Largest(readings);` copies the value, and writes to `copy` go nowhere. Since C# 7.3 a ref local can be pointed elsewhere with `peak = ref readings[0];`. A `ref readonly` return gives read-only access; a caller that keeps the reference needs a `ref readonly` local (CS8329 otherwise). The compiler only lets a method return a reference to storage that outlives the call, such as an array element, a field of a class or a `ref` parameter. It rejects a local with CS8168 and a by-value parameter with CS8166, because both die with the stack frame.

code

csharp · 25 lines
csharp
using System;
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

double[] readings = { 21.5, 48.0, 33.2 };

ref double peak = ref Largest(readings);   // ref local: an alias, not a copy
peak = 40.0;                               // writes readings[1]
Console.WriteLine(string.Join(" | ", readings));   // 21.5 | 40 | 33.2

double copy = Largest(readings);           // no 'ref' on the local: a copy
copy = 0.0;
Console.WriteLine(readings[1]);            // still 40

peak = ref readings[0];                    // ref reassignment (C# 7.3)
peak += 1.0;
Console.WriteLine(readings[0]);            // 22.5

static ref double Largest(double[] values)
{
    int best = 0;
    for (int i = 1; i < values.Length; i++)
        if (values[i] > values[best]) best = i;
    return ref values[best];               // the element lives in the array, on the heap
}

go deeper

for a junior

Know that a ref return gives back the storage itself, and that the caller needs ref on the local and on the call to write through it.

for a middle

Explain which storage may be returned by reference and why: array elements and class fields outlive the call, locals and by-value parameters do not.

for a senior

Catch the silent copy when a caller drops ref, and choose ref readonly for large structs exposed by a container so callers read without copying or mutating.

for a principal

Weigh the aliasing a ref-returning API hands to every caller against the copies it saves, and keep such APIs narrow and documented.

## Ref returns and ref locals A **ref return** is a method whose return type carries the `ref` modifier: it returns a reference to a variable (a storage location), not a copy of the variable's value. A **ref local** is a local variable declared with `ref` that holds such a reference and acts as an **alias**: reading it reads the original storage, and assigning to it writes the original storage. Ref locals and ref returns arrived in C# 7, `ref readonly` returns in C# 7.2, and reassigning a ref local with `= ref` in C# 7.3. ## The sensor example A monitoring loop wants to clamp the highest reading of a sensor array in place: ```csharp static ref double Largest(double[] values) { int best = 0; for (int i = 1; i < values.Length; i++) if (values[i] > values[best]) best = i; return ref values[best]; } ref double peak = ref Largest(readings); peak = 40.0; // readings[best] is now 40 ``` The method finds the index and returns a reference to that **array element**. The element lives inside the array object on the heap, so the reference stays valid after `Largest` returns; the garbage collector also tracks it and keeps the array alive while the reference exists. ## Copy or alias: where `ref` must appear | Caller writes | What the local holds | Effect of assigning 0 to it | |---|---|---| | `ref double p = ref Largest(r);` | an alias to the element | the array element becomes 0 | | `double p = Largest(r);` | a copy of the value | only the local changes | | `var p = Largest(r);` | a copy (`var` infers `double`) | only the local changes | | `ref var p = ref Largest(r);` | an alias | the array element becomes 0 | Forgetting the `ref` on the local is legal and silent, which is why a reviewer reads both ends of the call. A ref local can also be **reassigned**: `peak = ref readings[0];` points it at a different element, while `peak = 5;` writes through it. ## `ref readonly` returns `static ref readonly double Peek(double[] values) => ref values[^1];` returns an alias the caller may read but not write through. The caller stores it in a `ref readonly double` local; `ref double w = ref Peek(readings);` is rejected with CS8329 because it would turn a read-only reference into a writable one. The main use is returning a large struct from a collection-like type without copying it while still forbidding callers to modify it. It protects only this path: other code holding the array can still change the element. ## What may be returned by reference The compiler checks that a returned reference is **safe to escape** to the caller, which means its storage must outlive the method: - **Allowed:** an element of an array, a field of a class instance, a static field, a `ref` parameter, an element of a `Span<T>` received as a parameter, and the result of another ref-returning call made with such arguments. - **Rejected:** a local variable (CS8168, "Cannot return local 'best' by reference because it is not a ref local"), because it disappears when the frame is popped. - **Rejected:** a by-value parameter (CS8166), because it is a copy that also lives in the frame. - **Rejected:** an element of a span over `stackalloc` memory created inside the method (CS8352), because that memory is in the frame too. - **Rejected by default:** a struct method or property returning a reference to its own field (CS8170), since `this` in a struct is a reference only for the duration of the call. The `[UnscopedRef]` attribute from C# 11 lifts that where the caller's variable outlives the result. These are compile-time checks; nothing is verified when the code runs. ## When ref returns earn their place 1. **In-place updates** of an element chosen by a search, as in the sensor case, without returning an index for the caller to look up again. 2. **Large structs**, where returning `ref readonly` avoids copying the struct on every read. 3. **Low-level containers**, which expose element references the way `Span<T>`'s indexer returns `ref T`. The cost is aliasing: any code holding the ref local sees later writes to the slot and can write to it, so ref returns belong in narrow, well-named APIs rather than everywhere a value is read.

  • Why does ref double w = ref Peek(readings); fail when Peek returns ref readonly double?
    Binding a writable ref local to a read-only reference would let the caller write through it, so the compiler reports CS8329, "Cannot use method 'Peek' as a ref or out value because it is a readonly variable." Declare the local as `ref readonly double w = ref Peek(readings);`, or drop both `ref`s to take a copy.
  • Can a struct property return a ref to one of the struct's own fields?
    Not by default: the compiler reports CS8170, "Struct members cannot return 'this' or other instance members by reference," because `this` in a struct member is a reference valid only during the call. Marking the member `[UnscopedRef]` (System.Diagnostics.CodeAnalysis, C# 11) widens that lifetime, and the compiler then requires the caller's struct variable to outlive the returned reference.
  • Is static ref double First(Span<double> s) => ref s[0]; legal?
    Yes. A span parameter refers to memory owned by the caller, so a reference into it may be returned to that caller. What is rejected is a reference into a span the method created over its own `stackalloc` memory, which reports CS8352 because that memory dies with the frame.

  • A ref return copies the new value back into the array when the caller assigns it.
  • Writing var peak = Largest(readings) gives you a ref local automatically.
  • Returning ref to a local is fine because the caller reads it immediately.
  • A ref readonly return freezes the array element for all other code.
  • A ref local can never be pointed at a different variable once initialized.