Span and Memory
Span is a window
Span<T> is a pair of a pointer and a length:
it names a run of existing elements and owns no memory of its own. A
string, an array and a stack buffer can all be seen
through one, and passing a span costs two words.
The type is a ref struct: it lives on the stack and
cannot be stored in a field of a class, boxed, or used across an
await. That restriction is the price of having no
allocation at all.
A slice without a copy
int[] numbers = { 1, 2, 3, 4, 5 };
Span<int> middle = numbers.AsSpan(1, 3);
middle[0] = 20;
Console.WriteLine(string.Join(",", numbers));
ReadOnlySpan<char> year = "2026-11-20".AsSpan(0, 4);
Console.WriteLine(year.ToString());
Console.WriteLine(year.Length);
dotnet run
1,20,3,4,5
2026
4
AsSpan(1, 3) starts at index 1 and covers three
elements, so it sees 2, 3 and 4. Writing 20 into its first element wrote
into the original array at index 1, which the first line proves: a span is a
window, not a copy.
AsSpan(0, 4) on a string gives a
ReadOnlySpan<char> over the first four
characters, and ToString() materialises them into a
new string. A parser that walks a line character by character and cuts
fields out of it does all of that without allocating a string per field,
which is why the BCL itself takes spans almost everywhere.
stackalloc
A small span can point at a buffer of the current stack frame, so the buffer costs no heap allocation and is gone when the method returns:
Span<int> local = stackalloc int[3];
local[0] = 7;
Console.WriteLine(local[0]);
Console.WriteLine(local.Length);
dotnet run
7
3
The size must be a constant or small enough for the stack: a stackalloc of a million elements would overflow it and end the program with a stack overflow, which no exception can catch. The rule of thumb is a few hundred bytes, and an array above that.
Memory for the async case
A ref struct cannot cross an await, because the state machine moves the frame to the heap. Memory<T> is the heap-safe counterpart: it names the same kind of window and can be stored in a field or passed to an async method, at the cost of one allocation for the wrapper.
Memory<char> memory = "hello".ToCharArray();
ReadOnlySpan<char> view = memory.Span;
Console.WriteLine(view[0]);
Console.WriteLine(view.Length);
Console.WriteLine(view.Slice(1, 3).ToString());
dotnet run
h
5
ell
memory.Span is the read-only window over the buffer, and Slice(1, 3) takes three characters starting at the second. The pattern of a method that takes a Memory<T> and works through .Span inside is what lets the same code serve a synchronous and an asynchronous caller.
Exercises
- Write a method that takes a ReadOnlySpan<char> and returns the number of digits in it. Call it with a string and with a slice.
- Try to store a Span<int> in a field of a class. Read the error and say which restriction it names.
- Slice the same array twice, write through the first slice and read the second. What do you see, and why?
- Make the stack buffer 10 000 000 elements long and run it. What happens before an exception could be caught?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a Span<T>?
Answer
A window over existing elements: a pointer and a length
A span owns no memory and copies nothing; it names a run of elements that are already somewhere.
-
What does this program print?
int[] numbers = { 1, 2, 3, 4 }; Span<int> part = numbers.AsSpan(2, 2); Console.WriteLine(part[0]); Console.WriteLine(part.Length);Answer
3 / 2
The window starts at index 2, which holds 3, and covers two elements.
-
What does this program print?
int[] numbers = { 1, 2, 3 }; Span<int> part = numbers.AsSpan(1); part[0] = 9; Console.WriteLine(string.Join(",", numbers));Answer
1,9,3
The window starts at the second element, and a write through it changes the array itself.
-
Why can a Span<T> not be stored in a field of a class?
Answer
It is a ref struct and must live on the stack
A ref struct may not escape its stack frame, which a field of a heap object would allow.
-
What does this program print?
Span<int> buffer = stackalloc int[2]; buffer[1] = 5; Console.WriteLine(buffer[0] + buffer[1]);Answer
5
A stack buffer starts zeroed in a safe context, so the sum of 0 and 5 is 5.
-
Which type survives an await?
Answer
Memory<T>
Memory<T> is a normal struct over a heap buffer, while the span types are ref structs tied to the frame.
-
What does this program print?
ReadOnlySpan<char> text = "abcdef".AsSpan(1, 3); Console.WriteLine(text.ToString());Answer
bcd
The window starts at the second character and covers three, which is b, c and d.
-
What is the cost of passing a Span<T> to a method?
Answer
Two words, a pointer and a length, with no allocation
The span is a small struct of a reference and a length; passing it copies those two words and nothing else.
-
What happens when stackalloc asks for far more memory than the stack has?
Answer
The program dies with a stack overflow that cannot be caught
A stack overflow ends the process, which is why stackalloc is for small, bounded buffers.
-
What does this program print?
Memory<char> memory = "xy".ToCharArray(); ReadOnlySpan<char> span = memory.Span; Console.WriteLine(span.Length);Answer
2
The memory wraps a two-element array, and the span over it reports its two characters.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev