Skip to content

Span<T> and ref structs

Span<T>, ReadOnlySpan<T>, and ref structs enable slicing memory with minimal allocations and stack-only safety.

C# 7.2+ (2017)

Span<int> s = stackalloc int[4];
s[0] = 42;
ReadOnlySpan<int> r = s;
  • ref structs cannot be boxed, captured by lambdas, or stored in fields of reference types.
  • Great for parsing, IO, and interop; prefer when profiling shows pressure.