C# › Arrays, Span<T> & Memory<T>

How does Memory<T> differ from Span<T>, and when would you use Memory<T> instead?

Intermediate

Answer

Memory<T> is a heap-allocatable counterpart to Span<T> — since Span<T> is a ref struct restricted to the stack (can't be used in async methods, lambdas capturing it, or as a class field), Memory<T> can be stored anywhere and converted to a Span<T> (via .Span) only when you actually need to access the underlying data synchronously.
async Task ProcessAsync(Memory<byte> buffer) {
  await Task.Delay(10); // Span<T> couldn't survive this await, but Memory<T> can
  Span<byte> span = buffer.Span; // convert to Span<T> only when actually processing
  span[0] = 0xFF;
}
Real-world example Passing a buffer through an async I/O pipeline (like a network stream reader) where Span<T> couldn't cross an 'await' boundary.

Common follow-ups: Why exactly can't a Span<T> be used across an 'await' in an async method?