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

Span struct — API reference covering constructors, Slice, and ref struct constraints. Memory and Span usage guidelines — Microsoft guidance on when to use Span vs Memory, ownership rules, and async boundaries. Welcome to C# 7.2 and Span — .NET blog post introducing Span with motivation, design rationale, and early usage examples.
Whats next

Parent
02 Computer Science

Pages