skip to content

In C# 11 and later, what does a ref field in a ref struct let you build, and which rules does the compiler enforce?

level: seniorimportance: nice to knowfreq 15%

answer

  1. how Span<T> stores its start
  2. only inside a ref struct
  3. = versus = ref
  4. readonly in two positions
  5. the default is a null ref

basics

~20 s

A ref field stores a managed reference, letting a ref struct point at a variable it does not own; Span<T> is a ref T field plus a length. Only ref structs may declare one (CS9059), and it cannot refer to a ref struct (CS9050).

solid answer

~50 s

A `ref` field, such as `private ref double _slot;`, holds a reference to a variable rather than a value, so a ref struct like `PeakSlot` can stand for the largest element of a sensor array and write through to it. `_slot = ref values[best];` points the field; `_slot = 40.0;` writes the referenced element. `Span<T>` itself holds `internal readonly ref T _reference;` plus a length. The compiler allows a ref field only as an instance field of a ref struct (CS9059), forbids a ref field whose type is a ref struct (CS9050), and needs a runtime that supports ref fields, as .NET 10 does. `readonly ref` limits repointing to constructors and `ref readonly` forbids writes through the field. Lifetimes follow what the field was given: constructing a `PeakSlot` over a local and returning it is CS8347 plus CS8168. A default instance holds a null ref; reading through it throws `NullReferenceException`.

code

csharp · 27 lines
csharp
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

double[] readings = { 21.5, 48.0, 33.2 };
var peak = new PeakSlot(readings);
peak.Value = 40.0;                               // writes through the ref field
Console.WriteLine(string.Join(" | ", readings)); // 21.5 | 40 | 33.2

var empty = default(PeakSlot);
Console.WriteLine(Unsafe.IsNullRef(ref empty.Slot));  // True: a null ref

ref struct PeakSlot
{
    private ref double _slot;                    // ref field (C# 11), legal only in a ref struct
    public PeakSlot(double[] values)
    {
        int best = 0;
        for (int i = 1; i < values.Length; i++)
            if (values[i] > values[best]) best = i;
        _slot = ref values[best];
    }
    public PeakSlot(ref double slot) => _slot = ref slot;
    public ref double Slot => ref _slot;
    public double Value { get => _slot; set => _slot = value; }
}

go deeper

for a junior

Know that Span<T> is built from a reference to its first element plus a length, and that this reference is a ref field.

for a middle

Explain the difference between ref assignment and value assignment on a ref field, and the readonly ref versus ref readonly variants.

for a senior

Predict the escape errors when a ref struct is built over a local, and guard against a defaulted instance holding a null ref.

for a principal

Decide when a custom span-like ref struct is worth its rules, compared with an index into an array that every reviewer already understands.

## What a ref field is A **ref field** is a field declared with the `ref` modifier inside a ref struct: `private ref double _slot;`. Like a ref local, it holds a **managed reference** to a variable (an array element, a field, a local of a caller) instead of a copy of that variable's value. Ref fields shipped in **C# 11**, together with `scoped`, and need runtime support, which the runtime advertises as `RuntimeFeature.ByRefFields`; when compiling against a runtime without it the compiler reports "Target runtime doesn't support ref fields." ## How `Span<T>` uses one Before C# 11, `Span<T>` relied on an internal runtime type, `ByReference<T>`, that the runtime treated as a ref field without any language-level safety checking, and only the runtime's own code could use it. With real ref fields the declaration in the .NET 10 source reads: ```csharp public readonly ref struct Span<T> { internal readonly ref T _reference; private readonly int _length; } ``` So a span is literally a reference to its first element plus a count, which is why slicing creates no copy. Ref fields let any library build the same kind of type. ## Declaring and assigning In a ref struct that tracks the peak reading of a sensor array: - `_slot = ref values[best];` is **ref assignment**: the field now refers to that element. - `_slot = 40.0;` is **value assignment**: it writes 40 into the referenced element, not into the struct. - `public ref double Slot => ref _slot;` returns the reference onward. The `readonly` modifier can sit in two places: | Declaration | Repoint with `= ref` | Write through with `=` | |---|---|---| | `ref T f` | anywhere the field is accessible | yes | | `readonly ref T f` | only in a constructor or `init` accessor | yes | | `ref readonly T f` | anywhere | no | | `readonly ref readonly T f` | only in a constructor or `init` accessor | no | ## Rules the compiler enforces - **Only in a ref struct.** A ref field in a class or an ordinary struct is CS9059, "A ref field can only be declared in a ref struct," because the field would otherwise land on the heap. - **Not to a ref struct.** `ref Span<int> _s;` is CS9050, "A ref field cannot refer to a ref struct." The C# 11 design notes that allowing it would need new lifetime rules for scenarios the current rules assume cannot happen. - **Language version.** At LangVersion 10 the declaration reports CS8936 for the feature 'ref fields'. - **Escape follows the referent.** A `PeakSlot` constructed over a heap array may be returned freely; one constructed over a local may not leave the method that owns the local. ## Lifetime: a ref field follows what it was given ```csharp static PeakSlot FromLocal() { double local = 1.0; return new PeakSlot(ref local); // CS8347 and CS8168 } ``` The constructor's `ref double` parameter can be captured into the field, so the compiler treats the result as carrying the local's lifetime. Returning it would leave a reference to a dead stack slot; the SDK reports CS8347 on the constructor call and CS8168 on `local`. Building the same struct over an array element is fine, and the reference also keeps the array alive for the garbage collector while the struct is in use. ## Null refs A ref field has no initializer, so `default(PeakSlot)` holds a **null reference**: 1. `Unsafe.IsNullRef(ref empty.Slot)` returns `true` for it. 2. Reading or writing through it throws `NullReferenceException` at run time, like dereferencing a null object reference. 3. A type that can be defaulted should check `Unsafe.IsNullRef` before use, or document that a default instance is invalid. Ref fields are a tool for library authors building span-like views; application code rarely declares them, but knowing them explains what a span is.

  • What happens when code reads Value on a default PeakSlot?
    Its ref field is a null reference, so reading through it throws `NullReferenceException` at run time; the compiler does not stop it. `Unsafe.IsNullRef(ref empty.Slot)` returns `true` and lets a type detect the state first. Types with ref fields either check for it or document that their default value must not be used.
  • Why is ref Span<int> _s; rejected as a field?
    The compiler reports CS9050, "A ref field cannot refer to a ref struct." A reference to a span would carry two lifetimes, the reference's and the span's own, and the C# 11 design notes that allowing it requires new ref-safety rules beyond what shipped. Hold the span by value as an ordinary field of the ref struct instead.

  • Any struct can declare a ref field since C# 11.
  • A ref field is a raw pointer, so it requires an unsafe context.
  • Assigning _slot = value repoints the field at the new value.
  • A default ref struct's ref field refers to a zeroed value.
  • Span<T> in .NET 10 stores an array reference plus an integer offset.