C# ReadOnlySpan
last modified November 6, 2026
In this article we show how to use the ReadOnlySpan<T>
struct in C#.
A ReadOnlySpan<T> is a read-only view over a contiguous
region of memory. The memory can be an array, a string, a block allocated
with stackalloc, or unmanaged memory. A span stores only a
reference to the first element and a length; creating or slicing a span never
copies the data.
ReadOnlySpan<T> is a ref struct. It can live
only on the stack: it cannot be a field of a class, an element of a
collection, or a variable that is used across await. In exchange
for these restrictions, spans are very fast and can safely point into stack
memory. For heap-friendly views, .NET has ReadOnlyMemory<T>.
Many methods for spans are extension methods of the
MemoryExtensions class; for example IndexOf,
Trim, StartsWith, SequenceEqual, and
Split.
Creating spans
An array converts implicitly to a ReadOnlySpan<T>; a string
is turned into a span of characters with AsSpan.
int[] vals = [1, 2, 3, 4, 5, 6];
ReadOnlySpan<int> span = vals;
Console.WriteLine($"Length: {span.Length}");
Console.WriteLine($"First: {span[0]}, last: {span[^1]}");
Console.WriteLine($"Slice: [{string.Join(", ", span.Slice(1, 3).ToArray())}]");
Console.WriteLine($"Range: [{string.Join(", ", span[3..].ToArray())}]");
vals[0] = 100;
Console.WriteLine($"First after change: {span[0]}");
ReadOnlySpan<char> word = "falcon".AsSpan(1, 3);
Console.WriteLine($"Word part: {word}");
The span covers the whole array. The indexer, the ^ operator,
Slice, and ranges work as with arrays, but slicing returns a new
span over the same memory instead of a copy.
vals[0] = 100;
Console.WriteLine($"First after change: {span[0]}");
The span does not own the data. A change made to the array is visible through the span.
ReadOnlySpan<char> word = "falcon".AsSpan(1, 3);
AsSpan(1, 3) creates a span over three characters of the string
starting at index 1. No new string is created.
$ dotnet run Length: 6 First: 1, last: 6 Slice: [2, 3, 4] Range: [4, 5, 6] First after change: 100 Word part: alc
Read-only access
ReadOnlySpan<T> prevents writes through the span itself;
the data may still change through other references.
int[] vals = [5, 3, 8, 1];
Span<int> span = vals;
ReadOnlySpan<int> view = span;
span.Sort();
span[0] = 10;
Console.WriteLine($"view: [{string.Join(", ", view.ToArray())}]");
Console.WriteLine($"Max: {Max(vals)}");
static int Max(ReadOnlySpan<int> items)
{
int max = items[0];
foreach (int e in items)
{
if (e > max) max = e;
}
return max;
}
A Span<int> converts implicitly to a
ReadOnlySpan<int>. Sorting and assigning through the
writable span changes the array, and the read-only view reflects it.
An assignment such as view[0] = 1 does not compile; the
compiler reports error CS8331 because the indexer returns a read-only
reference.
static int Max(ReadOnlySpan<int> items)
ReadOnlySpan<T> is a good parameter type for methods that
only read data. The method accepts arrays, slices of arrays, and
stack-allocated memory, and the signature promises not to modify them.
$ dotnet run view: [10, 3, 5, 8] Max: 10
Working with text
MemoryExtensions provides string-like methods for character
spans.
string line = " Name: John Doe ";
ReadOnlySpan<char> s = line.AsSpan().Trim();
Console.WriteLine($"Trimmed: '{s}'");
Console.WriteLine($"Starts with 'name': {s.StartsWith("name", StringComparison.OrdinalIgnoreCase)}");
int colon = s.IndexOf(':');
ReadOnlySpan<char> key = s[..colon];
ReadOnlySpan<char> value = s[(colon + 1)..].TrimStart();
Console.WriteLine($"Key: {key}, value: {value}");
Console.WriteLine($"Value is 'john doe': {value.Equals("john doe", StringComparison.OrdinalIgnoreCase)}");
Console.WriteLine($"Contains 'Doe': {value.Contains("Doe", StringComparison.Ordinal)}");
Trim returns a smaller span; the original string is not changed
and no new string is allocated.
int colon = s.IndexOf(':');
ReadOnlySpan<char> key = s[..colon];
ReadOnlySpan<char> value = s[(colon + 1)..].TrimStart();
The key and the value are slices of the same string. They are converted to strings only when they are printed.
Console.WriteLine($"Value is 'john doe': {value.Equals("john doe", StringComparison.OrdinalIgnoreCase)}");
To compare a span with a string, use Equals,
StartsWith, or Contains with a
StringComparison value. Do not use the == operator;
for spans it checks whether both spans point to the same memory, not whether
they contain the same characters.
$ dotnet run Trimmed: 'Name: John Doe' Starts with 'name': True Key: Name, value: John Doe Value is 'john doe': True Contains 'Doe': True
Splitting without allocations
Since .NET 9, a ReadOnlySpan<char> can be split with the
Split extension method. It returns the ranges of the parts
instead of an array of strings.
string data = "12,4, 55,7 ,30";
ReadOnlySpan<char> span = data;
int sum = 0;
foreach (Range r in span.Split(','))
{
ReadOnlySpan<char> field = span[r].Trim();
int n = int.Parse(field);
Console.WriteLine($"'{field}' -> {n}");
sum += n;
}
Console.WriteLine($"Sum: {sum}");
Split returns a SpanSplitEnumerator that produces
Range values. The range is applied to the original span to get
the field.
int n = int.Parse(field);
int.Parse and the other parsing methods have overloads that take
a ReadOnlySpan<char>, so the number is parsed directly from
the slice.
$ dotnet run '12' -> 12 '4' -> 4 '55' -> 55 '7' -> 7 '30' -> 30 Sum: 108
Measuring allocations
The example sums the numbers of a comma-separated string, first with
string.Split and then with the span version.
string csv = string.Join(",", Enumerable.Range(1, 1000));
Console.WriteLine($"With strings: {Measure(() => SumStrings(csv))} bytes");
Console.WriteLine($"With spans: {Measure(() => SumSpans(csv))} bytes");
Console.WriteLine($"Sums: {SumStrings(csv)}, {SumSpans(csv)}");
static long Measure(Func<int> action)
{
action();
long before = GC.GetAllocatedBytesForCurrentThread();
action();
return GC.GetAllocatedBytesForCurrentThread() - before;
}
static int SumStrings(string csv)
{
int sum = 0;
foreach (string part in csv.Split(','))
{
sum += int.Parse(part);
}
return sum;
}
static int SumSpans(string csv)
{
ReadOnlySpan<char> span = csv;
int sum = 0;
foreach (Range r in span.Split(','))
{
sum += int.Parse(span[r]);
}
return sum;
}
GC.GetAllocatedBytesForCurrentThread returns the number of bytes
allocated by the current thread. Each method runs once before the measurement
so that one-time initialization is not counted.
foreach (string part in csv.Split(','))
string.Split allocates a string for each of the 1000 numbers
plus the array that holds them.
foreach (Range r in span.Split(','))
The span version allocates nothing; the parts are slices of the input.
$ dotnet run With strings: 39952 bytes With spans: 0 bytes Sums: 500500, 500500
Binary data
Spans are well suited for parsing binary formats. The example reads the header of a PNG image from a byte array.
using System.Buffers.Binary;
byte[] file = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A,
0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01, 0xE0, 0x08, 0x06];
ReadOnlySpan<byte> data = file;
ReadOnlySpan<byte> signature = [0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A];
Console.WriteLine($"PNG file: {data.StartsWith(signature)}");
ReadOnlySpan<byte> chunk = data[8..];
int length = BinaryPrimitives.ReadInt32BigEndian(chunk);
bool isHeader = chunk.Slice(4, 4).SequenceEqual("IHDR"u8);
Console.WriteLine($"First chunk: IHDR {isHeader}, {length} bytes");
int width = BinaryPrimitives.ReadInt32BigEndian(chunk[8..]);
int height = BinaryPrimitives.ReadInt32BigEndian(chunk[12..]);
Console.WriteLine($"Size: {width}x{height}");
A PNG file starts with an 8-byte signature followed by the
IHDR chunk, which contains the image width and height.
ReadOnlySpan<byte> signature = [0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A];
A collection expression assigned to a ReadOnlySpan<byte>
of constants does not allocate; the compiler stores the bytes in the
assembly's data.
int length = BinaryPrimitives.ReadInt32BigEndian(chunk);
bool isHeader = chunk.Slice(4, 4).SequenceEqual("IHDR"u8);
PNG stores numbers in big-endian byte order, which
BinaryPrimitives.ReadInt32BigEndian reads from the start of a
span. The u8 suffix makes a string literal a
ReadOnlySpan<byte> with its UTF-8 bytes, and
SequenceEqual compares two spans element by element.
$ dotnet run PNG file: True First chunk: IHDR True, 13 bytes Size: 640x480
params spans
Since C# 13, a params parameter can be a
ReadOnlySpan<T>.
Console.WriteLine(Sum(1, 2, 3));
Console.WriteLine(Sum(10, 20, 30, 40, 50));
int[] vals = [4, 5, 6];
Console.WriteLine(Sum(vals));
Console.WriteLine(Sum());
ReadOnlySpan<string> words = ["sky", "blue", "cup"];
Console.WriteLine(string.Join(" ", words));
static int Sum(params ReadOnlySpan<int> items)
{
int sum = 0;
foreach (int e in items)
{
sum += e;
}
return sum;
}
With params int[], every call with individual arguments
allocates an array. With params ReadOnlySpan<int>, the
compiler places the arguments in a buffer on the stack.
Console.WriteLine(Sum(vals)); Console.WriteLine(Sum());
An existing array can be passed as well, and a call without arguments gets an empty span.
Console.WriteLine(string.Join(" ", words));
Several framework methods, such as string.Join, have
params ReadOnlySpan<T> overloads.
$ dotnet run 6 150 15 0 sky blue cup
Stack memory
stackalloc allocates a buffer on the stack. Together with spans,
it can produce formatted text without heap allocations.
Span<char> buf = stackalloc char[64];
(string Name, double Price)[] items = [("coffee", 3.5), ("sandwich", 7.25), ("cake", 12)];
foreach (var (name, price) in items)
{
if (buf.TryWrite($"{name,-10}{price,8:F2}", out int written))
{
ReadOnlySpan<char> line = buf[..written];
Console.Out.WriteLine(line);
}
}
The 64-character buffer is released automatically when the method returns.
Keep stack buffers small; a large stackalloc can overflow the
stack.
if (buf.TryWrite($"{name,-10}{price,8:F2}", out int written))
TryWrite formats an interpolated string directly into the span.
It returns false if the buffer is too small.
ReadOnlySpan<char> line = buf[..written]; Console.Out.WriteLine(line);
Only the written part of the buffer is used. TextWriter has
overloads that accept a ReadOnlySpan<char>.
$ dotnet run coffee 3.50 sandwich 7.25 cake 12.00
ReadOnlyMemory
A span cannot be a parameter of an async method (error CS4012)
or a field of a class (error CS8345). In such cases we use
ReadOnlyMemory<T> and get a span from it when the data is
processed.
string text = "an old falcon flew over the river";
ReadOnlyMemory<char> mem = text.AsMemory();
int count = await CountAsync(mem, 'o');
Console.WriteLine($"Count of 'o': {count}");
var parts = new List<ReadOnlyMemory<char>> { mem[..6], mem[7..13], mem[^5..] };
foreach (ReadOnlyMemory<char> p in parts)
{
Console.WriteLine(p.Span);
}
static async Task<int> CountAsync(ReadOnlyMemory<char> data, char c)
{
await Task.Delay(10);
return data.Span.Count(c);
}
AsMemory creates a ReadOnlyMemory<char> over
the string. It can be sliced like a span, but it is an ordinary struct.
static async Task<int> CountAsync(ReadOnlyMemory<char> data, char c)
{
await Task.Delay(10);
return data.Span.Count(c);
}
The memory is passed to an asynchronous method. The Span
property gives a span for the synchronous work after the
await.
var parts = new List<ReadOnlyMemory<char>> { mem[..6], mem[7..13], mem[^5..] };
Memory slices can be stored in a list, which is not possible with spans.
$ dotnet run Count of 'o': 3 an old falcon river
Source
In this article we have worked with ReadOnlySpan<T> in C#.
Author
List all C# tutorials.