C# › Arrays, Span<T> & Memory<T>
What restrictions does the C# compiler enforce on Span<T> because it's a 'ref struct'?
IntermediateAnswer
Because Span<T> can point directly at stack memory, the compiler restricts it to prevent that memory from outliving its valid scope: it cannot be boxed, cannot be a field of a non-ref-struct class, cannot be used in async methods or iterators (yield return), and cannot be captured by a lambda or local function that might outlive the current stack frame.
// class Container { Span<int> data; } // Error: cannot use Span<T> as a field in a regular class
async Task Bad() {
Span<int> span = stackalloc int[10];
await Task.Delay(1); // Error: cannot use Span<T> across an await
}Real-world example Understanding why a Span<T>-based helper method can't be trivially converted into an async method or a yield-based iterator.