Glossary / ReadOnlySpan<T>
ReadOnlySpan
ReadOnlySpan<T> is a stack-only view over a contiguous sequence of T values that allows reads but prevents writes through that view. It provides allocation-free slicing and parsing for arrays, strings, stack memory, and other contiguous sources while preserving ref-struct lifetime safety.
Read-only view semantics
ReadOnlySpan<char> text = "lead engineer";
ReadOnlySpan<char> first = text[..4];
A read-only span does not make the underlying memory immutable: another alias may mutate an array while the span exists. For string-backed spans, the string itself is immutable. Slicing shares memory and carries offset/length. ReadOnlySpan<T> can be implicitly constructed from compatible arrays/spans and exposed by parsing APIs such as int.TryParse(ReadOnlySpan<char>, ...).
Because it is a ref struct, it cannot ordinarily be boxed, stored in a class, or captured; it is aimed at synchronous operations. ReadOnlyMemory<T> is the heap-storable async counterpart. Unsafe conversions can break the read-only guarantee and should remain tightly controlled.
Engineering guidance
Use for synchronous parsing, comparisons, and zero-copy APIs. Do not keep it beyond the backing memory's lifetime or assume read-only view means no concurrent mutation. Prefer string APIs for non-hot paths when they make code clearer; benchmark allocation-sensitive workloads.
Interview questions
- Does ReadOnlySpan copy? No; it views existing memory.
- Does read-only mean backing storage cannot change? No; other aliases can mutate it.
- Why stack-only? Its byref-like representation needs restricted lifetime guarantees.
- What is its async counterpart?
ReadOnlyMemory<T>. - Give a use case. Parsing substrings without allocating new strings.