Glossary / Span<T>

Span

Span<T> is a stack-only, mutable view over a contiguous region of memory containing T values. It can refer to arrays, stack-allocated memory, or unmanaged memory, enabling slicing and parsing without allocating new arrays. Its ref struct lifetime restrictions prevent it from escaping to ordinary heap storage.

Slicing and safety

Span<int> values = stackalloc int[] { 1, 2, 3, 4 };
Span<int> middle = values.Slice(1, 2);
middle[0] = 20; // changes values[1]

A span contains a reference and length; slicing creates another view, not a copy. Bounds are checked by safe APIs and indexers. Span<T> can point at managed array memory, and GC tracks references safely; MemoryMarshal and unsafe operations can bypass protections and require precise lifetime reasoning. A span cannot be stored in a class field, boxed, captured by ordinary lambdas, or survive across await/yield in unsupported contexts, though newer C# versions relax some restrictions under ref-safety analysis.

ReadOnlySpan<T> exposes read-only access. Spans are ideal for synchronous high-performance APIs; use Memory<T> for data that must be stored across async boundaries.

Engineering guidance

Use spans for slicing/parsing hot paths where allocation reduction matters. Do not retain a span beyond its backing memory lifetime. Be careful with stackalloc sizes and avoid large stack allocations. Benchmark and prefer simpler arrays/strings when performance needs do not justify ref-safety complexity.

Interview questions

  1. Does Slice copy? No; it creates a view over the same memory.
  2. Why is Span a ref struct? To constrain lifetime and prevent unsafe heap escape of byref-like memory.
  3. Can Span live across await? Traditionally no; newer C# versions allow some ref-like usage in async methods under scoped rules, but not across suspension when lifetime would be invalid.
  4. Span vs Memory? Span is stack-only synchronous view; Memory can be stored and used across async boundaries.
  5. When use stackalloc? Small bounded temporary buffers with known safe size.

References