🔧 Fix a Span Captured by a Lambda Throwing at Runtime
`Span<T>` is a `ref struct`, which the compiler restricts from being used inside a closure because a `ref struct` can point to stack-allocated or interior memory the garbage collector doesn’t track the way it tracks heap references, while a closure’s captured variables get hoisted into a heap-allocated object so they can outlive the method that created them. The compiler catches the most obvious violations at compile time with error CS8175, but a span passed indirectly through a generic wrapper, or into a local function later converted to a delegate, can sometimes slip past that static check and only fail at runtime with a confusing, low-level exception when the JIT actually tries to compile the closure.
🔎 The Problem
void Process(Span<char> buffer)
{
// Won't compile - CS8175, span captured by the lambda
// Action work = () => buffer[0] = 'x';
// Fix: do the span-touching work BEFORE any delegate or async boundary,
// then capture a plain copy of the value you actually need afterward.
buffer[0] = 'x';
int firstChar = buffer[0];
Action logWork = () => Console.WriteLine($"First char was {firstChar}");
logWork();
}
✅ Fix: Copy the Value Out Before You Capture Anything
- Never try to capture a `Span<T>`/`ReadOnlySpan<T>` itself inside a lambda, a local function converted to a delegate, or an async/iterator method — do all span-touching work synchronously, inline, before any delegate or async boundary is crossed.
- If you need a value FROM the span after that boundary, copy the specific data out into an ordinary non-ref-struct type — a char, an int, a string, or an array via `.ToArray()` — and capture that copy instead of the span.
- Treat any compiler error mentioning “ref struct,” “ref local,” or CS8175 as non-negotiable rather than looking for a workaround to silence it — the handful of ways to technically bypass the check are exactly the paths that produce a runtime crash instead of a compile-time one.
🚨 Why This Is Dangerous
- Because the whole point of the compiler’s restriction is to catch this at compile time, a case that slips past it and fails at runtime instead tends to do so with a confusing, low-level exception that gives no indication the actual root cause is a captured span.
A ref struct that escapes the compiler’s check doesn’t become safe to capture – it just fails somewhere less helpful.
