C# Reference ยท Strings and Text
String and ReadOnlySpan<char>
Reference for slicing and parsing C# text with ReadOnlySpan<char>: AsSpan, Slice, TryParse on spans, SpanSplit and when spans beat Substring.
Every Substring, Split and Trim on a string creates a new string on the heap. A ReadOnlySpan<char> is a window onto existing characters: it holds a reference and a length, allocates nothing, and can be sliced as often as you like. You get one from a string with AsSpan(), and many APIs accept spans directly.
Spans are ref struct types, so they live on the stack and have restrictions: no fields in normal classes, no use across await, and no capture in lambdas. When you need to keep the text, call ToString() to copy it into a real string.
ReadOnlySpan<char> word = "hello world".AsSpan(0, 5); Console.WriteLine(word.ToString()); // hello
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static ReadOnlySpan<char> AsSpan(this string? text) public static ReadOnlySpan<char> AsSpan(this string? text, int start) public static ReadOnlySpan<char> AsSpan(this string? text, int start, int length) public static ReadOnlySpan<char> AsSpan(this string? text, Range range) public readonly ref struct ReadOnlySpan<T> { public int Length { get; } public ReadOnlySpan<T> Slice(int start, int length); public T this[int index] { get; } public override string ToString(); // for ReadOnlySpan<char> }
| Name | Description |
|---|---|
text |
The string to view. null gives an empty span. |
start, length |
The window, in chars. |
range |
A C# range such as 1..4, usable with the indexer too. |
Returns: a view of the same memory; no characters are copied.
Errors / undefined behavior: ArgumentOutOfRangeException when the window does not fit. Indexing a span out of range throws IndexOutOfRangeException. A span is only valid while the original string or buffer is alive and unchanged.
Usage notes
- Why bother. Parsing a log line with
SplitandSubstringallocates a string for every field. The span version allocates nothing, which matters in hot paths and servers. - Most text APIs have span versions.
int.Parse,TryParse,TryFormat,string.Concat,StartsWith,IndexOf,Trim,SequenceEqualandCompareToall take spans. - Compare with
SequenceEqualorEquals(..., StringComparison).==on two spans compares the reference and length, not the characters. - Spans cannot be stored on the heap. You cannot keep one in a class field, use it in an
asyncmethod across anawait, or capture it in a lambda. UseReadOnlyMemory<char>for those cases. - Strings are immutable, spans over them are read-only. For a mutable window use
Span<char>over an array orstackalloc. AsSpan()is notToCharArray(). The first is a free view; the second copies.- Stack buffers.
stackallocis fast but limited; keep buffers small (a few hundred chars) and fall back toArrayPool<char>or a string for larger inputs. RangeandIndexwork.span[..3],span[^2..]andspan[1..^1]slice exactly as they do for arrays.