skip to content

In C#, what is a ref struct such as Span<T>, and which uses of an ordinary struct does the compiler reject for it?

level: juniorimportance: should knowfreq 48%

answer

  1. confined to the execution stack
  2. never reaches the managed heap
  3. no box, no array, no class field
  4. no capture by lambdas
  5. tearing and managed pointers

basics

~20 s

A ref struct is a stack-only struct, which lets it safely hold a span or a ref field. It cannot be boxed, be an array element, be a field of a class or ordinary struct, or be captured by a lambda.

solid answer

~50 s

`ref struct` marks a value type as stack-only; `Span<T>` and `ReadOnlySpan<T>` are the best-known examples. A span can point into `stackalloc` memory or into the middle of an array, so no copy of it may outlive that memory or land on the GC heap. The compiler therefore closes every path to the heap: a field in a class or a non-ref struct (CS8345), an array element (CS0611), a conversion to `object` or to an interface (CS0029 or CS0030, because it would box), and capture by a lambda or local function (CS8175), since captured variables move into a compiler-generated closure that can be a heap object. A ref struct may still be a local, a parameter, a return value or an instance field of another ref struct. C# 13 relaxed the rules for async methods, iterators, interfaces and generic type arguments, but none of these heap paths.

code

csharp · 20 lines
csharp
using System;

byte[] packet = { 0x01, 0x2A, 0x00 };
var reader = new PacketReader(packet);     // a local: allowed
Console.WriteLine(reader.ReadByte());      // 1
Console.WriteLine(reader.ReadByte());      // 42

// object boxed = reader;                  // CS0029: no boxing conversion
// var many = new PacketReader[4];         // CS0611: not an array element type
// Func<byte> next = () => reader.ReadByte();  // CS8175: no capture in a lambda

ref struct PacketReader                    // a field of a ref struct may be a span
{
    private readonly ReadOnlySpan<byte> _buffer;
    private int _pos;
    public PacketReader(ReadOnlySpan<byte> buffer) => _buffer = buffer;
    public byte ReadByte() => _buffer[_pos++];
}

// class Session { private PacketReader _reader; }   // CS8345: not in a class

go deeper

for a junior

Recall that Span<T> is a ref struct and list what it cannot do: be boxed, be an array element, be a field of a class or ordinary struct, or be captured by a lambda.

for a middle

Explain why each restriction exists: every one is a route to the managed heap, and a span on the heap could tear or hold a managed pointer the runtime cannot track.

for a senior

Read CS8345, CS0611, CS8175 and CS9244 in review and propose the repair each implies: make the container a ref struct, store an array with an offset, or pass the span as a parameter.

for a principal

Frame ref structs as a compile-time guarantee rather than a run-time check, and know which C# 13 relaxations a codebase can rely on before adopting them.

## What a ref struct is A **ref struct** is a struct declared with the `ref` modifier: `ref struct PacketReader { ... }`. The compiler guarantees that every instance lives on the **execution stack** (or in registers) and never on the **managed heap**, the memory the garbage collector owns. The best-known ref structs are `Span<T>` and `ReadOnlySpan<T>`, declared in the base class library as `public readonly ref struct Span<T>`. In metadata the compiler marks such a type with `IsByRefLikeAttribute`, and reflection reports it through `Type.IsByRefLike`, which is why runtime APIs call these **byref-like types**. You write your own ref struct when a type needs to hold a span. A binary protocol reader is the classic case: ```csharp ref struct PacketReader { private readonly ReadOnlySpan<byte> _buffer; private int _pos; public PacketReader(ReadOnlySpan<byte> buffer) => _buffer = buffer; public byte ReadByte() => _buffer[_pos++]; } ``` Declare `PacketReader` as a plain `struct` and the span field is rejected with CS8345, because an ordinary struct can itself end up on the heap. ## Why the stack-only rule exists The C# 7.2 design for span safety gives two reasons a span must stay on the stack: 1. **Tearing.** A span is a reference plus a length. Writing both is not atomic, so if a span sat in a heap object shared between threads, one thread could read a new reference with an old length and index past the end of the memory, which breaks type safety in code that contains no `unsafe` keyword. 2. **Managed pointers.** `Span<T>` holds a managed pointer (a `ref T` field) that can point into the middle of an array or into stack memory. The runtime does not support managed pointers as fields of heap objects. Both problems disappear if the value can never leave the stack, and the compiler enforces that statically, at compile time, with no run-time check. ## What the compiler rejects | What you write | Result | Diagnostic from the C# 14 compiler | |---|---|---| | A `PacketReader` or `ReadOnlySpan<byte>` field in a class | rejected | CS8345 | | The same field in an ordinary (non-ref) struct | rejected | CS8345 | | `new PacketReader[4]` | rejected | CS0611 | | `object o = reader;` | rejected | CS0029 (CS0030 with an explicit cast) | | `() => reader.ReadByte()` or a local function using `reader` | rejected | CS8175 | | `List<PacketReader>` | rejected | CS9244 | The text of CS8345 states the rule exactly: a field of a ref struct type is allowed only if it is an instance member of a ref struct. Each row is a route to the heap: - **Boxing** copies the value into a heap object, so there is no conversion to `object`, `ValueType` or an interface, implicit or explicit. - **Arrays** are heap objects, so a ref struct cannot be an element type. - **Lambdas and local functions** move captured variables into a compiler-generated closure, a heap object in the lambda case. - **Generic type arguments** are rejected because generic code could box or store `T`, unless the type parameter opts in (see below). ## What stays allowed - Locals, parameters (by value or by `ref`), and return values. - Instance fields of another ref struct, which is how `PacketReader` holds its span. - Instance methods, properties, constructors, and a pattern-based `Dispose` method that a `using` statement can call. - `readonly ref struct`, which also requires every instance field to be `readonly` (CS8340 otherwise). ## What C# 13 changed C# 13 kept every heap path closed but relaxed four rules that had been stricter than they needed to be: - A ref struct local may appear in an **async method** or an **iterator**, as long as no `await` or `yield return` falls between its uses. - A ref struct may **implement an interface**, though it still cannot be converted to it. - A generic type parameter may declare **`allows ref struct`**, after which a ref struct can be its type argument. - The same release let ref locals into async methods and iterators. The last three have their own questions; the core rule, that a ref struct value never reaches the heap, has not moved since C# 7.2. ## Reading the errors in review 1. CS8345 on a field means the containing type must become a ref struct itself, or the field must become something storable, such as an array with an offset or a `Memory<T>`. 2. CS0611 or CS9244 means a collection was asked to hold the value; keep the underlying data in the collection instead. 3. CS8175 means a lambda or local function captured the variable; pass the span in as a parameter of a separate method.

  • Why may PacketReader hold a ReadOnlySpan<byte> field when a class may not?
    Because `PacketReader` is itself a ref struct, the compiler applies the same stack-only rules to it, so the span can never reach the heap through its container. CS8345 allows a ref struct field only as an instance member of a ref struct. Declare the reader as a plain `struct` and the same field is rejected, since an ordinary struct can be boxed or stored in an array or class.
  • Can you write List<PacketReader> or pass a ref struct as a generic type argument?
    Not to `List<T>`: the compiler reports CS9244 because `List<T>` does not declare `allows ref struct` on `T`. Since C# 13 a generic type or method can opt in with that anti-constraint, and the .NET 10 library annotates some generics such as `Func<T, TResult>`, `Action<T>` and `IEnumerable<T>`. A collection that stores its elements in an array can never opt in, because a ref struct cannot be an array element.
  • What does readonly ref struct add to ref struct?
    It adds the `readonly struct` guarantee: every instance field must be `readonly`, or the compiler reports CS8340, and no member may change the instance's state. `Span<T>` and `ReadOnlySpan<T>` are both declared `readonly ref struct`, because the view itself never changes; writing through a `Span<T>` changes the memory it points at, not the span.

  • A ref struct is just a struct that is always passed by reference.
  • A Span<T> field in a class is fine as long as the object is short-lived.
  • Boxing a span works; it only costs an extra allocation.
  • A ref struct can never contain another ref struct.
  • The runtime throws when a span escapes to the heap, so the compiler need not check.

Assumes C# 14; the core ref struct restrictions date from C# 7.2, and C# 13 relaxed only the async, iterator, interface and generic-argument rules.