🔧 C#: Fix a Ref Struct Escaping Scope Through a Local Function
A ref struct like Span<T> is restricted by the compiler specifically to prevent it from outliving the stack frame that created it, since it may wrap memory such as a stackalloc buffer that isn’t valid once that frame unwinds. A local function declared inside the same method is still compiled as logically part of that method for most purposes, but the moment it’s converted to a delegate, passed where an Action is expected, stored in a variable, or captured by an async state machine, the compiler has to move its captured variables onto the heap to survive past the original call, and that is exactly the conversion a ref struct capture must be rejected for.
🔎 The Problem
void ProcessChunk(Span<byte> buffer)
{
void LocalWrite() => Console.WriteLine(buffer.Length);
// Fine as long as LocalWrite is only ever called directly -
// the compiler keeps the ref struct capture on the stack.
// The moment this local function is converted to a delegate
// (Action action = LocalWrite;) the compiler must reject it,
// since a heap-allocated delegate cannot safely carry a
// stack-only Span capture past the current frame's lifetime
LocalWrite();
}
✅ Fix: Keep the Capture Out of Reach of a Delegate
- Pass the ref struct’s needed data, such as its length or a computed value, as an ordinary parameter into the local function instead of capturing the ref struct itself by closure, so converting the function to a delegate is never even possible to get wrong.
- If the local function genuinely needs the whole span, keep it strictly non-capturing of outer ref struct state and call it only directly, never storing it in a variable or passing it where a delegate type is expected.
- Enable the project’s ref-safety analyzers and treat any warning about a ref struct capture as a hard build error, since this entire class of bug is exactly what those specific compiler diagnostics exist to catch early.
🚨 Why This Is Dangerous
- A Span capture that genuinely escapes its valid stack lifetime through a delegate conversion is undefined behavior, not just a style issue, and failures from it tend to show up as sporadic data corruption or crashes that are extremely difficult to reproduce reliably.
A ref struct’s whole safety model is never let me outlive my frame — a local function that quietly becomes a delegate is one of the few ways a program can still try to break that promise.



