C# Reference ยท Types and Literals
Span<T> and Memory<T>
Reference for Span<T>, ReadOnlySpan<T> and Memory<T> in C#: slicing without copying, stackalloc, ref struct limits, async use and common pitfalls.
Span<T> is a window onto a contiguous block of memory: part of an array, a stackalloc buffer, a string or native memory. Slicing a span creates another window over the same memory without copying anything. ReadOnlySpan<T> is the same view without write access, and string converts to ReadOnlySpan<char> implicitly.
Memory<T> and ReadOnlyMemory<T> are the heap-friendly siblings. They can be stored in fields and used across await, and you call .Span to get a Span<T> when you need to work with the data.
int[] data = [1, 2, 3, 4, 5]; Span<int> middle = data.AsSpan(1, 3); middle[0] = 20; Console.WriteLine(string.Join(",", data));
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 readonly ref struct Span<T> public readonly ref struct ReadOnlySpan<T> public readonly struct Memory<T> public readonly struct ReadOnlyMemory<T>
| Member | Description |
|---|---|
Length, IsEmpty |
Number of elements. |
this[int] |
Reference to an element (throws IndexOutOfRangeException). |
Slice(start), Slice(start, length) or span[a..b] |
A smaller view over the same memory. |
CopyTo(Span<T>), TryCopyTo |
Copies; CopyTo throws if the destination is too short. |
Fill(value), Clear() |
Overwrites all elements. |
ToArray() |
Copies into a new array. |
Memory<T>.Span |
Gets a span over the memory. |
Helpers live in MemoryExtensions: AsSpan, IndexOf, Contains, SequenceEqual, StartsWith, Trim, Split (.NET 9), Reverse, Sort, BinarySearch.
Errors: ArgumentOutOfRangeException for slices outside the bounds, ArrayTypeMismatchException when creating a Span<T> over an array of a covariant type.
Usage notes
Span<T>is aref struct. It can live only on the stack: it cannot be a field of a class, be boxed, captured by a lambda or used in anasyncmethod across anawait, or be a generic type argument (before C# 13'sallows ref struct). UseMemory<T>for those cases.- Slicing is O(1) and allocates nothing.
data[1..3]on an array copies, whiledata.AsSpan()[1..3]does not. - Views see changes. Writing through a span changes the array underneath, and the other way round.
stackallocand spans.Span<int> s = stackalloc int[16];needs nounsafe. Keep sizes small; a largestackalloccan overflow the stack and crash the process.- Strings are read-only.
"text".AsSpan()givesReadOnlySpan<char>; the string is never modified. - Parsing without allocating.
int.Parse,TryParse,Guid.ParseandDateTime.ParsehaveReadOnlySpan<char>overloads. - Lifetime rules. The compiler prevents returning a span over a local
stackallocbuffer. Spans pointing at heap data may be returned. - Equality.
==on spans compares the reference and length, not contents; useSequenceEqual. - Cost of
Memory<T>.Span. It is cheap but not free; call it once outside a loop.