Span<T> and ref structs
Overview
Section titled โOverviewโSpan<T>
, ReadOnlySpan<T>
, and ref structs enable slicing memory with minimal allocations and stack-only safety.
Introduced In
Section titled โIntroduced InโC# 7.2+ (2017)
Example
Section titled โExampleโSpan<int> s = stackalloc int[4];s[0] = 42;ReadOnlySpan<int> r = s;
Gotchas & Best Practices
Section titled โGotchas & Best Practicesโ- 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.