What restrictions does the C# compiler enforce on Span<T> because it's a 'ref struct'?
Short answer
Because Span 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…
Advertisement
AModel answer
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.
Likely follow-ups
- What's the underlying CLR reason these specific restrictions exist for ref structs?
Related topics