Skip to main content

How to Take Part of a ReadOnlySpan<T> with a Range in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

all[..3] takes the first three items of a ReadOnlySpan<int>, just as it would from an array, but nothing is copied: the result is a span over the same items. When you need a copy, ToArray() makes one.

Microsoft's reference describes ReadOnlySpan<T> like this: Provides a type-safe and memory-safe read-only representation of a contiguous region of arbitrary memory. Ranges work on it. The tutorial on ranges: Not only arrays support indices and ranges. You can also use indices and ranges with string, Span<T>, or ReadOnlySpan<T>.

What sets a span apart is what a range gives back. The same tutorial: On the other hand, if it's a System.Span<T> or a System.Memory<T>, the result references the same backing store, which means there is no copy and the operation is O(1).

Syntax​

Syntax
ReadOnlySpan<T> <part> = <span>[<start>..<end>];
T[] <copy> = <part>.ToArray();
PartWhat it is
<span>A ReadOnlySpan<T>, where T is the type of the items, such as int
<start>..<end>The items from position <start> up to, but not including, <end>. Positions start at 0. Leave out <start> to begin at the first item, or <end> to go to the last
^<n>A position counted from the end, as in ^2.. for the last two items
.ToArray()Copies the items into a new array

The range operator, in the C# reference: The left-hand operand is an inclusive start of a range. The right-hand operand is an exclusive end of a range.

The Example​

A console app called SpanRange keeps six lap times in a ReadOnlySpan<int>, takes three parts of it with ranges, prints them, and then changes the array to show that a part is a view and a ToArray() copy isn't.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n SpanRange
cd SpanRange
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/SpanRange/SpanRange.csproj:
Determining projects to restore...
Restored /Users/you/source/SpanRange/SpanRange.csproj (in 40 ms).
Restore succeeded.

dotnet new console -n SpanRange creates a folder named SpanRange with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or SpanRange.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the span and the ranges:

Program.cs (the span and the ranges)
// Six lap times in seconds. An array converts to ReadOnlySpan<int> by itself.
int[] laps = [62, 58, 61, 57, 60, 59];
ReadOnlySpan<int> all = laps;

// Ranges take parts of the span.
ReadOnlySpan<int> firstThree = all[..3];
ReadOnlySpan<int> middle = all[2..4];
ReadOnlySpan<int> lastTwo = all[^2..];
  • ReadOnlySpan<int> all = laps; turns the array into a span without any conversion code.
  • all[..3] is the first three items, all[2..4] the items at positions 2 and 3, and all[^2..] the last two.
  • Each part, often called a slice, is a ReadOnlySpan<int> too.

Then the printing:

Program.cs (printing the parts)
// ToArray copies the items into a new array, which string.Join can print.
Console.WriteLine($"First three: {string.Join(", ", firstThree.ToArray())}");
Console.WriteLine($"Middle: {string.Join(", ", middle.ToArray())}");
Console.WriteLine($"Last two: {string.Join(", ", lastTwo.ToArray())}");

ToArray() copies a part's items into a new int[], and string.Join puts commas between them.

Then a change to the array:

Program.cs (a slice and a copy)
// A slice reads the array itself. A copy made with ToArray doesn't change.
int[] copy = firstThree.ToArray();
laps[0] = 70;
Console.WriteLine($"After laps[0] = 70: the slice starts with {firstThree[0]}, the copy with {copy[0]}");

copy is taken before the change, and laps[0] = 70 changes the first lap in the array.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
First three: 62, 58, 61
Middle: 61, 57
Last two: 60, 59
After laps[0] = 70: the slice starts with 70, the copy with 62

macOS-style terminal window titled Terminal — SpanRange showing dotnet run printing First three: 62, 58, 61, Middle: 61, 57 and Last two: 60, 59, then a line saying that after the first lap changed to 70, the slice starts with 70 and the copy with 62

  • ..3 gave positions 0, 1 and 2: 62, 58, 61.
  • 2..4 gave 61 and 57, positions 2 and 3: the end isn't included.
  • ^2.. gave the last two, 60 and 59.
  • After the change, firstThree[0] was 70: the slice reads the array itself. The copy from ToArray() still held 62. The reference on ToArray: Copies the contents of this read-only span into a new array.

The Complete File​

macOS-style code window titled Program.cs — SpanRange showing six lap times in an array turned into a ReadOnlySpan of int, three parts taken with the ranges ..3, 2..4 and ^2.., each part printed through ToArray and string.Join, and a copy made with ToArray before the first lap changes to 70

Program.cs
// Six lap times in seconds. An array converts to ReadOnlySpan<int> by itself.
int[] laps = [62, 58, 61, 57, 60, 59];
ReadOnlySpan<int> all = laps;

// Ranges take parts of the span.
ReadOnlySpan<int> firstThree = all[..3];
ReadOnlySpan<int> middle = all[2..4];
ReadOnlySpan<int> lastTwo = all[^2..];

// ToArray copies the items into a new array, which string.Join can print.
Console.WriteLine($"First three: {string.Join(", ", firstThree.ToArray())}");
Console.WriteLine($"Middle: {string.Join(", ", middle.ToArray())}");
Console.WriteLine($"Last two: {string.Join(", ", lastTwo.ToArray())}");

// A slice reads the array itself. A copy made with ToArray doesn't change.
int[] copy = firstThree.ToArray();
laps[0] = 70;
Console.WriteLine($"After laps[0] = 70: the slice starts with {firstThree[0]}, the copy with {copy[0]}");

Common Mistakes​

MistakeWhat happensDo this instead
Printing a span with Console.WriteLine(firstThree)error CS1503: Argument 1: cannot convert from 'System.ReadOnlySpan<int>' to 'bool'Copy it and join the items, as the example does: string.Join(", ", firstThree.ToArray())
Calling LINQ on a span, as in firstThree.Select(lap => lap * 2)error CS0411: The type arguments for method 'ImmutableArrayExtensions.Select<T, TResult>(ImmutableArray<T>, Func<T, TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. The span isn't a sequence LINQ can read: the reference says ref struct types cannot implement any interface typeCopy it first: firstThree.ToArray().Select(lap => lap * 2) gave 124, 116, 122
A range that ends past the last item, such as all[..10] on six itemsUnhandled exception. System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.Cap the end at the length: all[..Math.Min(10, all.Length)] gave all six laps

FAQ​

Is a range the same as Slice?​

On a span, it gives the same items: all[2..4] and all.Slice(2, 2) both gave 61, 57. The difference is the second number, which is an end for a range and a length for Slice. The reference: Forms a slice out of the current read-only span starting at a specified index for a specified length.

Does a range on the array copy the items?​

Yes. int[] firstThree = laps[..3]; still started with 62 after laps[0] = 70. The tutorial: When taking a range from an array, the result is an array that is copied from the initial array, rather than referenced.

When should I call ToArray?​

Only when you need an array, such as for LINQ or string.Join. The reference: This method performs a heap allocation and data copy, and therefore, should be avoided if possible.

Conclusion​

A range such as all[..3] or all[^2..] on a ReadOnlySpan<T> gives a smaller span over the same items, without copying them. Call ToArray() on the part when you need an array of your own, and keep the end of the range within the span's length.

Additional Resources​