C# › Arrays, Span<T> & Memory<T>
What is the role of Span<T> and Memory<T> in .NET, and why can't Span<T> be used inside an async method?
AdvancedAnswer
Span<T> is a lightweight, stack-only type representing a contiguous slice of memory (an array, a portion of an array, or stack-allocated memory) without copying the underlying data, making it ideal for high-performance scenarios like parsing buffers -- because it's a ref struct living strictly on the stack, it cannot be used across an 'await' boundary, since the stack frame isn't preserved while an async method is suspended. Memory<T> solves this by providing similar slicing capability but supporting heap storage, making it safe to hold across asynchronous operations and pass into async methods.
int[] numbers = { 1, 2, 3, 4, 5 };
Span<int> span = numbers.AsSpan(1, 3); // references {2, 3, 4} without copying -- but stack-only
// For async code, use Memory<T> instead, since it can survive across an 'await'
Memory<int> memory = numbers;
Memory<int> slice = memory.Slice(1, 3); // same slicing capability, safely usable in async methodsReal-world example A high-throughput binary protocol parser uses Span<T> for synchronous, allocation-free parsing of incoming byte buffers, but switches to Memory<T> specifically for the portion of the pipeline that needs to await a network read before continuing to process the same buffer.