Span

Intro

Span<T> is a stack-only view over contiguous memory. It does not own data, it only points to existing memory (array, stackalloc buffer, or unmanaged memory). Use it when you need high-performance slicing/parsing with minimal allocations.

Span<T> gives bounds-checked access to a contiguous region with very low overhead:

Structure

graph LR
    A[array zero ten] --> B[array one twenty] --> C[array two thirty] --> D[array three forty]
    S[span start two length two] --> C
    S --> D

Example

Span<int> values = stackalloc int[] { 10, 20, 30, 40 };
Span<int> tail = values.Slice(2); // 30, 40

tail[0] = 300;
Console.WriteLine(values[2]); // 300

Pitfalls

Tradeoffs

Questions


Whats next