C# Span
last modified November 6, 2026
In this article we show how to use the Span<T> type in C#.
Span<T> is a memory-efficient way to work with contiguous
memory regions, such as arrays, strings, and stack-allocated memory. It
avoids unnecessary memory allocations and improves performance.
The Span type is particularly useful when we need to work with
slices of arrays or strings without creating copies.
Span<T> is a ref struct that provides a
type-safe and memory-safe representation of a contiguous region of memory. It
can point to memory on the stack, on the managed heap, or to unmanaged
memory. Unlike arrays, Span does not allocate memory; it is a
view into existing memory. ReadOnlySpan<T> is its
read-only counterpart; strings can be viewed only as
ReadOnlySpan<char>.
C# create Span
The following example creates a Span from an array.
int[] numbers = [1, 2, 3, 4, 5];
Span<int> span = numbers.AsSpan();
span[0] = 10;
Console.WriteLine(string.Join(", ", numbers));
Span<int> span2 = numbers;
span2[^1] = 50;
Console.WriteLine(string.Join(", ", numbers));
Console.WriteLine(span2.Length);
Modifying the Span also modifies the original array, because
Span provides a view into the array's memory.
Span<int> span = numbers.AsSpan();
A Span is created from an array using the AsSpan
method.
Span<int> span2 = numbers; span2[^1] = 50;
An array is also implicitly convertible to a span. Spans support indexes from the end.
$ dotnet run 10, 2, 3, 4, 5 10, 2, 3, 4, 50 5
C# slice Span
The following example slices a Span to work with a subset of
its elements.
int[] numbers = [1, 2, 3, 4, 5];
Span<int> span = numbers;
Span<int> slice = span.Slice(1, 3);
slice[0] = 20;
Console.WriteLine(string.Join(", ", numbers));
Span<int> tail = span[3..];
tail.Fill(0);
Console.WriteLine(string.Join(", ", numbers));
A slice is again a view; it does not copy the data.
Span<int> slice = span.Slice(1, 3); slice[0] = 20;
The Slice method creates a Span that represents
three elements starting at index 1. Modifying the slice also modifies the
original array.
Span<int> tail = span[3..]; tail.Fill(0);
The range syntax is a shorter alternative to Slice. The
Fill method sets all elements of the slice to zero.
$ dotnet run 1, 20, 3, 4, 5 1, 20, 3, 0, 0
C# Span with strings
The following example uses ReadOnlySpan<char> to work with
parts of strings without allocating new strings.
string text = "an old falcon";
ReadOnlySpan<char> span = text.AsSpan();
ReadOnlySpan<char> slice = span.Slice(7, 6);
Console.WriteLine(slice.ToString());
Console.WriteLine(span[3..6].Equals("old", StringComparison.Ordinal));
Console.WriteLine(span.StartsWith("an"));
ReadOnlySpan<char> date = "2026-11-06";
int year = int.Parse(date[..4]);
int month = int.Parse(date[5..7]);
int day = int.Parse(date[8..]);
Console.WriteLine($"{day}.{month}.{year}");
Taking a Substring creates a new string object; slicing a span
does not.
ReadOnlySpan<char> slice = span.Slice(7, 6); Console.WriteLine(slice.ToString());
We get a view of the word falcon. The ToString
method creates a string from the span when we really need one.
Console.WriteLine(span[3..6].Equals("old", StringComparison.Ordinal));
Spans of characters can be compared with strings directly.
int year = int.Parse(date[..4]);
Many parsing methods accept a ReadOnlySpan<char>. We parse
the parts of a date without creating substrings.
$ dotnet run falcon True True 6.11.2026
C# stackalloc with Span
The stackalloc expression allocates a block of memory on the
stack. Assigned to a Span, it can be used safely without the
unsafe keyword.
Span<int> span = stackalloc int[] { 1, 2, 3, 4, 5 };
span[0] = 10;
Console.WriteLine(string.Join(", ", span.ToArray()));
Span<char> buffer = stackalloc char[32];
if (DateTime.UnixEpoch.TryFormat(buffer, out int written, "yyyy-MM-dd"))
{
Console.WriteLine(buffer[..written].ToString());
}
int n = 12345;
Span<byte> digits = stackalloc byte[10];
int count = 0;
while (n > 0)
{
digits[count++] = (byte) (n % 10);
n /= 10;
}
digits[..count].Reverse();
Console.WriteLine(string.Join("", digits[..count].ToArray()));
Stack memory is released automatically when the method returns; it puts no pressure on the garbage collector. It is suitable for small, short-lived buffers.
Span<char> buffer = stackalloc char[32]; if (DateTime.UnixEpoch.TryFormat(buffer, out int written, "yyyy-MM-dd"))
The TryFormat methods write the text into a provided buffer
instead of returning a new string. The written variable holds
the number of characters written.
digits[..count].Reverse();
We store the digits of a number in a stack buffer in reverse order and then reverse the used part in place.
$ dotnet run 10, 2, 3, 4, 5 1970-01-01 12345
C# Span methods
The MemoryExtensions class provides many methods for spans,
similar to those of arrays and LINQ.
Span<int> vals = [7, 3, 9, 1, 5, 3];
vals.Sort();
Console.WriteLine(string.Join(", ", vals.ToArray()));
Console.WriteLine(vals.IndexOf(5));
Console.WriteLine(vals.Contains(9));
Console.WriteLine(vals.BinarySearch(7));
vals.Reverse();
Console.WriteLine(string.Join(", ", vals.ToArray()));
int[] target = new int[3];
vals[..3].CopyTo(target);
Console.WriteLine(string.Join(", ", target));
Console.WriteLine(vals[..3].SequenceEqual(target));
Console.WriteLine(vals.Count(3));
We sort, search, reverse, copy, and compare span elements.
Span<int> vals = [7, 3, 9, 1, 5, 3];
Since C# 12, a span can be initialized with a collection expression.
Console.WriteLine(vals.BinarySearch(7));
The BinarySearch method works on sorted data; it returns the
index of the value.
vals[..3].CopyTo(target);
The CopyTo method copies the elements to another span or array.
Console.WriteLine(vals.Count(3));
The Count method counts the occurrences of a value.
$ dotnet run 1, 3, 3, 5, 7, 9 3 True 4 9, 7, 5, 3, 3, 1 9, 7, 5 True 2
C# split span
Since .NET 9, a ReadOnlySpan<char> can be split without
allocations. The Split method returns the ranges of the parts,
not new strings.
ReadOnlySpan<char> csv = "falcon,12,sky, owl ,7";
foreach (Range r in csv.Split(','))
{
ReadOnlySpan<char> field = csv[r].Trim();
if (int.TryParse(field, out int num))
{
Console.WriteLine($"number: {num}");
}
else
{
Console.WriteLine($"word: {field}");
}
}
We parse a comma-separated line.
foreach (Range r in csv.Split(','))
{
ReadOnlySpan<char> field = csv[r].Trim();
Each Range is used to slice the original span. The
Trim method narrows the slice.
if (int.TryParse(field, out int num))
The TryParse method accepts the span directly.
$ dotnet run word: falcon number: 12 word: sky word: owl number: 7
C# Memory
Since Span is a ref struct, it lives only on the
stack. It cannot be a field of a class, be boxed, or be used across an
await. Attempting these produces errors such as:
error CS8345: Field or auto-implemented property cannot be of type 'Span<int>' unless it is an instance member of a ref struct. error CS4007: Instance of type 'System.Span<int>' cannot be preserved across 'await' or 'yield' boundary.
For such cases, there is Memory<T>. It represents the same
kind of memory region, but it is a regular struct. When we need to access the
data, we get a span from its Span property.
var data = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
var parser = new Parser(data);
await parser.ProcessAsync();
class Parser(byte[] data)
{
private readonly Memory<byte> buffer = data;
public async Task ProcessAsync()
{
Memory<byte> header = buffer[..2];
Memory<byte> body = buffer[2..];
await Task.Delay(10);
Span<byte> span = body.Span;
span[0] = 30;
Console.WriteLine($"header: {string.Join(", ", header.ToArray())}");
Console.WriteLine($"body: {string.Join(", ", body.ToArray())}");
Console.WriteLine($"data: {string.Join(", ", data)}");
}
}
The Parser class keeps a Memory<byte> field
and uses it in an async method.
Memory<byte> header = buffer[..2]; Memory<byte> body = buffer[2..]; await Task.Delay(10);
Memory can be sliced like a span and survives the
await.
Span<byte> span = body.Span; span[0] = 30;
After the await, we get a span and modify the data. All views
share the same underlying array.
$ dotnet run header: 1, 2 body: 30, 4, 5, 6, 7, 8 data: 1, 2, 30, 4, 5, 6, 7, 8
C# first-class spans
C# 14 introduced first-class span types. The language defines implicit
conversions from arrays to Span<T> and
ReadOnlySpan<T>, and from Span<T> to
ReadOnlySpan<T>. These conversions also apply to
extension method receivers and generic type inference.
int[] vals = [1, 2, 3, 4, 5, 6];
Console.WriteLine(Sum(vals));
Console.WriteLine(Sum(vals.AsSpan(2)));
Console.WriteLine(vals.StartsWith([1, 2]));
ReadOnlySpan<int> ros = vals;
Console.WriteLine(ros.Length);
static int Sum(ReadOnlySpan<int> data)
{
int sum = 0;
foreach (var e in data)
{
sum += e;
}
return sum;
}
A method taking ReadOnlySpan<int> accepts arrays, array
slices, and spans.
Console.WriteLine(vals.StartsWith([1, 2]));
The StartsWith method is an extension method of
ReadOnlySpan<T>. In C# 14, it can be called directly on an
array, without AsSpan.
$ dotnet run 21 18 True 6
C# Span allocations
The following example compares the memory allocated by string operations and by span operations. We parse the same line 100,000 times.
string line = "id=4523;name=falcon;speed=389;habitat=cliffs";
long before = GC.GetAllocatedBytesForCurrentThread();
int sum1 = 0;
for (int i = 0; i < 100_000; i++)
{
foreach (var pair in line.Split(';'))
{
sum1 += pair.Substring(pair.IndexOf('=') + 1).Length;
}
}
long after = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($"string: {sum1}, allocated {(after - before) / 1024 / 1024} MB");
before = GC.GetAllocatedBytesForCurrentThread();
int sum2 = 0;
for (int i = 0; i < 100_000; i++)
{
ReadOnlySpan<char> span = line;
foreach (Range r in span.Split(';'))
{
ReadOnlySpan<char> pair = span[r];
sum2 += pair[(pair.IndexOf('=') + 1)..].Length;
}
}
after = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($"span: {sum2}, allocated {after - before} bytes");
We measure the allocated memory with
GC.GetAllocatedBytesForCurrentThread.
foreach (var pair in line.Split(';'))
{
sum1 += pair.Substring(pair.IndexOf('=') + 1).Length;
}
The string.Split method allocates an array and a string for each
part; Substring allocates another string.
foreach (Range r in span.Split(';'))
{
ReadOnlySpan<char> pair = span[r];
sum2 += pair[(pair.IndexOf('=') + 1)..].Length;
}
The span version computes the same result by slicing views of the original string. It does not allocate any memory. Less garbage means less work for the garbage collector, which matters in hot code paths such as parsers and servers.
$ dotnet run string: 1900000, allocated 36 MB span: 1900000, allocated 0 bytes
Source
In this article we have shown how to use the Span type in C#
for memory-efficient operations.
Author
List all C# tutorials.