Using ReadOnlySpan in C# for Slicing and Validation
ReadOnlySpan in C# enables allocation-free slicing and validation of strings and buffers. Includes practical parsing examples, ref struct restrictions, and performance trade-offs.

When you need to parse a substring, validate a byte sequence, or process a slice of a buffer without creating a new array or string, ReadOnlySpan<T> in C# lets you work directly with the underlying memory. ReadOnlySpan<T> is a ref struct that represents a contiguous region of memory you can only read. The span value itself is not allocated on the heap, which makes it useful in performance-sensitive paths where avoiding allocations matters.
The most common use is to avoid string allocations during text processing. Instead of calling Substring and paying for a new string, you can create a ReadOnlySpan<char> that points into the original string and operate on that. This is especially relevant in parsers, protocol handlers, and logging pipelines where the same buffer is processed repeatedly.
Creating a ReadOnlySpan Over a String
Use AsSpan() to get a ReadOnlySpan<char> from a string. Current .NET versions also support an implicit conversion, but using AsSpan() makes the intent explicit and works across more target frameworks. You can also create a span over an array, an array segment, or memory from a Memory<T>.
string message = "order:12345:paid";
ReadOnlySpan<char> span = message.AsSpan();AsSpan() does not copy the string's data. The span points directly at the first character of the string. You can then use the span's Slice method to get a subset without allocating a new string.
int firstColon = span.IndexOf(':');
ReadOnlySpan<char> idPart = span.Slice(0, firstColon);This creates a new span that references the same underlying memory as the original string. No characters are copied. The Slice method returns a ReadOnlySpan<char> that starts at the specified index and has the specified length.
Reading and Validating Data Without Allocation
Once you have a ReadOnlySpan<char>, you can enumerate it, compare it, or pass it to methods that accept ReadOnlySpan<char>. The .NET base class library includes many methods that accept spans, such as int.Parse overloads, Guid.Parse, and IPAddress.TryParse. This lets you parse a specific segment of a string without creating a substring.
public bool TryParseOrderId(string line, out int orderId)
{
ReadOnlySpan<char> span = line.AsSpan();
int colonIndex = span.IndexOf(':');
if (colonIndex < 0)
{
orderId = 0;
return false;
}
ReadOnlySpan<char> idSpan = span.Slice(0, colonIndex);
return int.TryParse(idSpan, out orderId);
}int.TryParse has an overload that accepts ReadOnlySpan<char>. The same applies to other numeric types and many parsing APIs. This pattern eliminates the Substring allocation that would otherwise occur if you converted the slice to a string first.
Slicing Without Copying: How It Works
ReadOnlySpan<T> is a ref struct that stores a reference to the start of the region and the length. The Slice method returns a new ref struct with an adjusted reference and length. There is no object allocation, and the operation completes in constant time.
ReadOnlySpan<char> full = "abcdef".AsSpan();
ReadOnlySpan<char> middle = full.Slice(2, 2); // "cd"For a string or array, the span holds an interior reference to the original data plus a length. When you slice it, you adjust the reference and length rather than copying data. That is why slicing a span is cheap and does not put pressure on the garbage collector.
Practical Scenario: Parsing Key-Value Pairs
Consider a simple key-value parser for a configuration line. Without spans, you might write code that creates multiple substring allocations. With ReadOnlySpan<char>, you can process the input without heap allocations for the parsed pieces.
public static void ParseKeyValue(ReadOnlySpan<char> line)
{
int equalsIndex = line.IndexOf('=');
if (equalsIndex < 0) return;
ReadOnlySpan<char> key = line.Slice(0, equalsIndex);
ReadOnlySpan<char> value = line.Slice(equalsIndex + 1);
Console.WriteLine($"Key: {key.ToString()} Value: {value.ToString()}");
}The ToString() calls in the example produce strings, but the span operations themselves do not allocate. If you need to log the values, the conversion is necessary. However, if you only need to compare or transform the value, you can avoid converting to a string entirely.
Performance Considerations
The main performance advantage of ReadOnlySpan<T> is the reduction in heap allocations. Creating a substring or an array slice forces the runtime to allocate new memory and copy the elements. A span slice does not allocate and does not copy. This reduces garbage collection pressure, which can improve throughput in high-frequency code paths.
There is a more subtle benefit: ReadOnlySpan<T> can be used with stack-allocated memory via stackalloc. Because a ref struct cannot be boxed and the compiler tracks its escape, a span can safely reference stack memory as long as it does not outlive the stack frame. This enables patterns that would be risky with arrays because arrays are heap objects.
Span<byte> buffer = stackalloc byte[256];
ReadOnlySpan<byte> data = buffer;
// populate data and process it without additional allocationsThis is valuable when handling network packets or file buffers where you want to avoid allocating a byte array for every operation. The stack is the right place for short-lived, small-sized buffers.
When ReadOnlySpan Is Not the Right Choice
The restrictions around ref structs mean you cannot use ReadOnlySpan<T> as a field in a class or as a generic type argument. You also cannot use it in async methods because an async method is rewritten by the compiler into a state machine that must preserve locals across await points, and a ref struct cannot be stored in that context. If you need to keep the data for later consumption or process it asynchronously, materialize it into a string or array first.
public async Task ProcessAsync(ReadOnlySpan<char> span) // compile error
{
// await is not allowed with a span parameter in scope
await Task.Delay(10);
}The compiler prevents this pattern because the async state machine cannot safely hold a ref struct. The same restriction applies to iterators, and a span cannot be captured in a lambda in a way that would let it outlive the current stack frame.
Stackalloc and Reference Restrictions
Because ReadOnlySpan<T> is a ref struct, a stackalloc buffer can be exposed as a span only within the current stack frame. The compiler's ref-safety rules are designed to keep that span from escaping, so returning a stackalloc-backed span is not a valid pattern.
public ReadOnlySpan<byte> CreateSpan()
{
Span<byte> buffer = stackalloc byte[10];
return buffer; // Invalid: stack memory is gone after return
}Do not use this pattern. The underlying stack memory is no longer valid once the method returns, and the caller would be left with a dangling span. Use stackalloc only for spans that remain in the current method.
Compatibility and .NET Versions
ReadOnlySpan<T> was introduced in .NET Core 2.1 and .NET Standard 2.1. To use it with .NET Framework, you need the System.Memory NuGet package. That package supplies the span types, but it does not add every existing API as a span overload. For example, numeric parsing overloads such as int.TryParse(ReadOnlySpan<char>, out int) require a runtime or library that provides the overload. Check the target framework before assuming a given API accepts a span.
When targeting modern .NET (Core 3.0 or later), the majority of string and numeric parsing APIs have span overloads. The trend in the BCL is to add span-based methods to reduce allocations. Before using a particular method with a span, verify that the target framework includes the overload.
Decision Criteria for Using ReadOnlySpan in C#
Choose ReadOnlySpan<T> when you have a hot path that processes many small slices of the same buffer or string. Typical cases include parsers, serialization, and binary protocol decoding. If the data is processed once and then discarded, spans offer significant savings.
If the data needs to be stored, sent to another thread, or included in an async operation, materialize it into a string or array. There is no point fighting the compiler restrictions; the cost of one string allocation is often acceptable outside the hottest path.
For line-by-line processing of small strings, a manual loop using ReadOnlySpan<char> can outperform Split because Split creates an array of substrings. However, code that avoids Split is more complex. Use that approach when profiling shows that allocation pressure is the bottleneck. In general, reach for ReadOnlySpan when you need to extract multiple values from a single buffer and you want to minimize allocations.
Advanced Slicing with Multiple Delimiters
You can combine Slice with methods like IndexOfAny to split on multiple separators. This is useful for parsing CSV-like input without allocating substrings.
ReadOnlySpan<char> line = "name;age;city";
int current = 0;
while (true)
{
int nextSemicolon = line.Slice(current).IndexOf(';');
int length = nextSemicolon < 0 ? line.Length - current : nextSemicolon;
ReadOnlySpan<char> field = line.Slice(current, length);
ProcessField(field);
if (nextSemicolon < 0) break;
current += nextSemicolon + 1;
}This loop processes each field without creating a single string. The ProcessField method can accept a ReadOnlySpan<char> and handle the field directly. This pattern is common in high-throughput log parsers or telemetry pipelines.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.