skip to content

In C# 13 and later, how can a ref struct PacketReader implement an interface and be passed to generic code without ever being boxed?

level: seniorimportance: nice to knowfreq 20%

answer

  1. implement, but never convert
  2. the conversion would box
  3. an anti-constraint on T
  4. constrained calls on the value
  5. every member, defaults included

basics

~20 s

Since C# 13 a ref struct may implement an interface, but converting it to that interface is rejected because it would box. Generic code opts in with where T : IByteSource, allows ref struct and then calls the interface members on T directly.

solid answer

~50 s

C# 13 accepts `ref struct PacketReader : IByteSource`, yet `IByteSource s = reader;` is still CS0029 and passing the reader to an `IByteSource` parameter is CS1503, since both would box it. The interface becomes useful through generics. A type parameter rejects ref structs by default (CS9244); adding the anti-constraint `allows ref struct` widens it, as in `static int Sum<T>(ref T source) where T : IByteSource, allows ref struct`. The compiler then holds `T` to ref struct rules inside the method: no conversion to `object` (CS0029), no `T[]` (CS0611), no capture by lambdas. Interface calls on `T` compile to constrained calls on the value, so nothing is boxed. A ref struct must implement every interface member itself, even one with a default body (CS9245). In .NET 10 many library generics carry the anti-constraint, such as `Func<T, TResult>`, `Action<T>`, `IEnumerable<T>` and `IEquatable<T>`, but not `List<T>`.

code

csharp · 43 lines
csharp
using System;

var reader = new PacketReader(new byte[] { 7, 8, 9 });
Console.WriteLine(Sum(ref reader));           // 24
Console.WriteLine(Sum(ref reader));           // 0: same reader, already drained

var array = new ArraySource(new byte[] { 1, 2 });
Console.WriteLine(Sum(ref array));            // 3: a class works too

// IByteSource s = reader;                   // CS0029: would box the ref struct

static int Sum<T>(ref T source) where T : IByteSource, allows ref struct
{
    int total = 0;
    while (source.TryRead(out byte b)) total += b;   // constrained call, no boxing
    return total;
}

interface IByteSource { bool TryRead(out byte value); }

ref struct PacketReader : IByteSource           // C# 13: ref struct implements an interface
{
    private ReadOnlySpan<byte> _buffer;
    private int _pos;
    public PacketReader(ReadOnlySpan<byte> buffer) => _buffer = buffer;
    public bool TryRead(out byte value)
    {
        if (_pos < _buffer.Length) { value = _buffer[_pos++]; return true; }
        value = 0;
        return false;
    }
}

sealed class ArraySource(byte[] data) : IByteSource
{
    private int _pos;
    public bool TryRead(out byte value)
    {
        bool ok = _pos < data.Length;
        value = ok ? data[_pos++] : (byte)0;
        return ok;
    }
}

go deeper

for a junior

Remember that since C# 13 a ref struct can implement an interface, but can never be stored in a variable of that interface type.

for a middle

Explain why the conversion is banned, boxing to the heap, and how a generic method with allows ref struct calls the interface without boxing.

for a senior

Design a generic reader API with allows ref struct and ref T parameters, and know the limits it imposes on the method body.

for a principal

Weigh the versioning risk of ref structs implementing interfaces from other assemblies, where an added default member breaks builds and callers.

## What C# 13 added Up to C# 12 a ref struct could not implement interfaces and could not be a generic type argument, so a `PacketReader` over a `ReadOnlySpan<byte>` could share no abstraction with an array-backed reader. **C# 13** (shipped with .NET 9) added two connected features: - **Ref struct interfaces**: a ref struct may list interfaces it implements. - **The `allows ref struct` anti-constraint**: a generic type parameter may declare that ref structs are acceptable type arguments. Neither feature weakens the core rule that a ref struct value never reaches the heap. ## Implementing is not converting An interface variable holds a reference, so converting a struct to an interface **boxes** it into a heap object. For a ref struct that remains illegal: | Code with `PacketReader : IByteSource` | Result | |---|---| | `IByteSource s = reader;` | CS0029 | | `Describe(reader)` where `Describe(IByteSource s)` | CS1503 | | `Read(reader)` where `Read<T>(T s) where T : IByteSource` | CS9244, `T` does not allow ref structs | | `Sum(ref reader)` where `T : IByteSource, allows ref struct` | compiles | | `IByteSource` with a default-bodied member the struct omits | CS9245 | The interface is therefore never a *type you store the reader as*; it is a *contract generic code can call*. ## Opting generic code in ```csharp static int Sum<T>(ref T source) where T : IByteSource, allows ref struct { int total = 0; while (source.TryRead(out byte b)) total += b; return total; } ``` `allows ref struct` is called an **anti-constraint** because it widens the set of permitted type arguments instead of narrowing it: `Sum` now accepts `PacketReader` and also ordinary classes or structs that implement `IByteSource`. Calls such as `source.TryRead` compile to **constrained calls**, which invoke the struct's method directly on the value without boxing. Taking `ref T` rather than `T` matters for a mutable reader: a by-value `T` would advance a copy, and the caller's reader would not move. ## What the generic method gives up Because `T` might be a ref struct, the compiler checks the method body as if it were one: - No conversion of `T` to `object` or to an interface (CS0029). - No arrays of `T` (CS0611), and therefore no `List<T>` or other array-backed collection of `T`. - No capture of a `T` variable in a lambda or local function (CS9108 for a parameter). - No passing `T` on to another generic that lacks `allows ref struct` (CS9244). Those limits are the price of accepting spans and span-wrapping readers without boxing. ## Default interface members A default interface method's body would run with `this` typed as the interface, which for a ref struct would mean boxing. So a ref struct **must implement every instance member** of the interfaces it lists, including ones with default bodies; otherwise the compiler reports CS9245. The documentation warns of a versioning cost: if a library you depend on adds a default member to an interface your ref struct implements, recompiling breaks with CS9245, and running against the new library without recompiling makes the runtime throw when that default member is called. ## In the base class library .NET 9 added `allows ref struct` to many generic definitions in the base class library. On .NET 10 the public surface shows it on, among others: 1. Delegates: `Func<T, TResult>`, `Action<T>`, `Predicate<T>`, `Comparison<T>`. 2. Interfaces: `IEnumerable<T>`, `IEnumerator<T>`, `IEquatable<T>`, `IComparable<T>`, `IEqualityComparer<T>`. 3. Span callbacks: the `TArg` of `SpanAction<T, TArg>` and `ReadOnlySpanAction<T, TArg>`. Collections that store elements in arrays, such as `List<T>`, do not and cannot carry it. Ref structs could already be used by `using` through a pattern-based `Dispose` method; since C# 13 they may also implement `IDisposable`, and the compiler still prefers the pattern method when both exist.

  • Why does Sum take ref T instead of T?
    `PacketReader` is a mutable struct whose read position lives in its `_pos` field. A by-value `T` parameter would receive a copy, advance the copy's position, and leave the caller's reader where it was. With `ref T` the method works on the caller's variable, which is why the second `Sum(ref reader)` in the example returns 0.
  • What breaks if a library adds a default member to an interface your ref struct implements?
    Recompiling your ref struct fails with CS9245 until you implement the new member, because a ref struct cannot use default bodies. If you upgrade the library without recompiling and code calls the new member on your type, the runtime throws when that default member is called. The docs therefore flag implementing another assembly's interface on a ref struct as a source and binary versioning risk.

  • A ref struct implementing IDisposable can be stored in an IDisposable variable.
  • allows ref struct restricts T so that only ref structs are accepted.
  • Generic code with allows ref struct boxes T to call interface members.
  • A ref struct can rely on an interface's default method bodies.
  • List<PacketReader> works since C# 13 because ref structs may be type arguments.

Assumes C# 14; ref struct interfaces and the allows ref struct anti-constraint arrived in C# 13 with .NET 9, and LangVersion 12 rejects them with CS9202.