Understanding the CLR constraints on ref struct types (like Span<T> and ReadOnlySpan<T>):
Because ref struct instances contain interior pointers directly into stack memory, the CLR guarantees they never escape to the managed heap where they could outlive their stack frames.
Forbidden in C#:
- Cannot be boxed (
object o = mySpan;// Compiler Error) - Cannot be a field of a normal class or struct
- Cannot be used in
asyncmethods acrossawaitboundaries (because async state machines are lifted to the heap upon suspension!) - Cannot be captured in lambda closures.
In .NET, use Memory<T> / ReadOnlyMemory<T> when buffer references need to cross async/await boundaries safely!