1. Introduction
Imagine you have a large array of data, for example bytes read from a file. You want to process a fragment — read a part as a string or just pass a segment of data to a method. In the "old" style you'd copy those bytes into a new array — that's slow and uses memory. What if there are dozens or hundreds of such fragments?
Here's the hero — Span<T>. It's a special struct that describes a slice (view) over an array (or any contiguous memory), without copying data, just pointing to the required region. Important: Span<T> is not a new collection, it's a safe "window" into an existing array!
Main features and limitations of Span<T>
- Span<T> is a structure (value type) representing a "window" into memory and does not copy elements.
- It refers only to contiguous memory: an array, part of an array, a stackalloc block, string memory via special methods, or memory in unsafe code.
- Span<T> lives on the stack. You can't store it in a class field or return it directly from async methods.
- It guarantees type safety: memory access without manual pointer work (unless you use unsafe).
Briefly about new C# 14 capabilities
C# 14 expands working with slices: handy ranges .. and indices-from-end ^1, improved pattern matching for arrays and slices, and other syntactic sugar. We'll return to this at the end.
2. How to create a Span<T>?
Let's start with a simple array and create a span:
int[] numbers = { 10, 20, 30, 40, 50, 60 };
Span<int> midSpan = new Span<int>(numbers, 2, 3); // take 3 elements starting from the 3rd element (index 2)
Now midSpan points to elements 30, 40, 50 — it's not a copy, but a view of the "live" array elements. Modifying them through the span changes the original array.
midSpan[0] = 100;
Console.WriteLine(numbers[2]); // Will print 100
Why not use array slices directly?
Classic LINQ slicing creates a new array:
int[] slice = numbers.Skip(2).Take(3).ToArray(); // <-- this creates a copy!
That's costly in time and memory. Span fixes extra copies — and works not only with numbers.
3. More ways to create Span<T>
Existing array
Span<int> mySpan = numbers; // Implicit conversion from array to Span
Part of an array
int[] numbers = {10, 20, 30, 40, 50, 60};
Span<int> part = numbers.AsSpan(1, 4); // 4 elements starting at index 1: {20, 30, 40, 50}
Stack memory (stackalloc)
Span<T> allows allocating arrays on the stack:
Span<byte> buffer = stackalloc byte[128];
for (int i = 0; i < buffer.Length; i++)
buffer[i] = (byte)i;
Stack memory is fast and freed automatically when exiting the method. But size must be reasonable — megabytes on the stack are unacceptable.
Strings and ReadOnlySpan<char>
Strings in .NET are immutable, so use ReadOnlySpan<char>:
string greeting = "Hello, C# world!";
ReadOnlySpan<char> span = greeting.AsSpan(7, 8); // "C# world"
Console.WriteLine(span.ToString()); // C# world
4. Let's assemble an example!
using System;
class Program
{
static void Main()
{
int[] orderTotals = { 100, 200, 300, 400, 500, 600, 700 };
Console.WriteLine("Full order history: ");
foreach (int total in orderTotals)
Console.Write(total + " ");
Console.WriteLine();
Console.WriteLine("Print orders from 2 to 4 (indexes 1-3):");
Span<int> recentOrders = orderTotals.AsSpan(1, 3);
foreach (int t in recentOrders)
Console.Write(t + " ");
Console.WriteLine();
// Mutate data via Span
recentOrders[1] = 999;
Console.WriteLine("After modification through Span:");
foreach (int total in orderTotals)
Console.Write(total + " ");
Console.WriteLine();
}
}
The slice recentOrders really works directly with the array — it's not a copy.
5. Safety, performance and checks
- Economical memory usage: no unnecessary copies.
- Bounds checks protect from going outside the array.
- JIT optimizations give very fast access (without unsafe).
Interaction with methods
Methods can accept Span<T> or ReadOnlySpan<T>. If you don't plan to modify data — use ReadOnlySpan<T>.
static int Sum(Span<int> slice)
{
int sum = 0;
foreach (var item in slice)
sum += item;
return sum;
}
int[] data = { 1, 2, 3, 4, 5, 6, 7 };
Console.WriteLine(Sum(data.AsSpan(2, 3))); // 3+4+5=12
6. Using ranges
Starting with C# 8, ranges .. and indices-from-end ^ are available — they work great with slices.
int[] arr = { 10, 20, 30, 40, 50, 60 };
Span<int> span = arr[2..5]; // indexes 2,3,4 - i.e. 30, 40, 50
In a range the start index is inclusive, the end is exclusive.
Indices-from-end
int lastElement = arr[^1]; // last element (60)
Span<int> lastTwo = arr[^2..]; // two last elements (50, 60)
Ranges and strings
string code = "SpanMagic!";
var mid = code[4..9]; // "Magic"
This slice is a ReadOnlySpan<char>; to get a string, call ToString().
7. Modern patterns for working with slices (C# 14)
New patterns simplify deconstructing arrays and slices.
if (arr is [10, 20, .. var rest]) // .. captures the "tail" of the array
{
Console.WriteLine("Start matched, tail:");
foreach (var x in rest)
Console.WriteLine(x);
}
if (arr is [.., 50, 60])
Console.WriteLine("Array ends with 50, 60");
Comparison: Array, ArraySegment and Span
| Type | Mutable | Copies data? | Can be on stack | Class/struct | Can be class fields |
|---|---|---|---|---|---|
|
yes | - | no | class | yes |
|
yes | no | no | struct | yes |
|
yes | no | yes | struct | no |
|
no | no | yes | struct | no |
In other words, Span<T> is an evolution of ArraySegment<T>: more performant and safer.
8. Common mistakes and pitfalls
Attempting to store Span<T> in a class field. Don't: fields live on the heap, but Span<T> must live on the stack. Use ArraySegment<T> or indices for addressing.
Returning/storing Span<T> from async methods. Not allowed: asynchrony breaks the stack. Pass data differently — for example, as an array, Memory<T>/ReadOnlyMemory<T>.
Wrong range when creating a slice. Going out of bounds causes a runtime exception. Always check length and boundaries before forming a slice.
Forgetting that a span reflects the original data. Any change via Span<T> mutates the source array. If you need an independent copy — explicitly copy the data.