C# Expert · Lesson 1 · On the house

Span<T> and allocation-free slicing

Span, ReadOnlySpan, stackalloc, and slicing without copying. Lesson 1 is free — on the house.

Lessons · C# Expert · Lesson 1 of 10 · On the house

Span<T> and allocation-free slicing

Span, ReadOnlySpan, stackalloc, and slicing without copying.

Illustration for C#
Lesson 1 is on the house.

Span<T> is a view over contiguous memory (array, stack, native). Slicing with span[2..5] or Slice creates a new view, not a copy.

ReadOnlySpan<char> lets you parse substrings without allocating: "12,34".AsSpan() then int.Parse(span[..2]).

stackalloc int[16] allocates on the stack into a Span<int>; keep it small (a few KB) to avoid stack overflow.

Span is a ref struct: it can't be boxed, stored in a class field, captured by lambdas, or used across await. Use Memory<T> when you need to store or await.

Writes through a span change the underlying array.

Span

int[] data = [1, 2, 3, 4, 5, 6];
Span<int> mid = data.AsSpan(1, 3);
mid[0] = 20;
Console.WriteLine(string.Join(",", data));

ReadOnlySpan<char> line = "2026-10-09".AsSpan();
int year = int.Parse(line[..4]);
int day = int.Parse(line[8..]);
Console.WriteLine(year + day);

Span<int> buf = stackalloc int[4];
for (int i = 0; i < buf.Length; i++) buf[i] = i * i;
int sum = 0;
foreach (var v in buf) sum += v;
Console.WriteLine(sum);
Match this when you type.

Quiz

Does span slicing copy the data?

Quiz

Why can't Span<T> be a class field?

Quiz

What should you use instead of Span across an await?

Quiz

What does data print after mid[0] = 20?

Check

Match the still for: Span<T> and allocation-free slicing.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.