ZetCode

C# ranges and indices

last modified November 15, 2026

This article shows how to use the index from end operator ^ and the range operator .. in C#. We work with arrays, strings, spans, lists, and custom types.

Ranges and indices were added in C# 8. The ^ operator creates an index counted from the end of a sequence: ^1 is the last element, ^2 the one before it. The .. operator creates a range that selects a part of a sequence: arr[1..4] returns the elements at positions 1, 2, and 3.

Both operators are backed by two structs from the System namespace. Index stores a position and a flag telling whether it is counted from the start or from the end. Range stores a start and an end Index. The start of a range is inclusive and the end is exclusive, so the length of a..b is b - a.

Index from end

The ^n index is equivalent to Length - n. It spares us from repeating the name of the collection.

Program.cs
string[] words = ["sky", "cup", "war", "rock", "tree", "falcon"];

Console.WriteLine(words[0]);
Console.WriteLine(words[^1]);
Console.WriteLine(words[^2]);
Console.WriteLine(words[words.Length - 2]);

Index last = ^1;
Index third = 2;

Console.WriteLine($"{last} {last.IsFromEnd} {last.Value}");
Console.WriteLine($"{third} {third.IsFromEnd} {third.Value}");
Console.WriteLine(words[third]);
Console.WriteLine(last.GetOffset(words.Length));

try
{
    Console.WriteLine(words[^0]);
}
catch (IndexOutOfRangeException e)
{
    Console.WriteLine(e.Message);
}

We access elements of an array from both ends.

Console.WriteLine(words[^1]);
Console.WriteLine(words[^2]);
Console.WriteLine(words[words.Length - 2]);

The words[^2] and words[words.Length - 2] expressions return the same element.

Index last = ^1;
Index third = 2;

An index can be stored in a variable of type Index. An int converts implicitly to an index counted from the start.

Console.WriteLine(last.GetOffset(words.Length));

The GetOffset method converts an index to a position from the start for a collection of the given length.

Console.WriteLine(words[^0]);

The ^0 index points one past the last element, like words[words.Length], so it throws an exception. It is valid, however, as the end of a range.

$ dotnet run
sky
falcon
tree
tree
^1 True 1
2 False 2
war
5
Index was outside the bounds of the array.

Ranges

A range is written as start..end. Both parts are optional: an omitted start means 0 and an omitted end means ^0. Applying a range to an array creates a new array.

Program.cs
int[] vals = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

Show("vals[2..5]", vals[2..5]);
Show("vals[..3]", vals[..3]);
Show("vals[7..]", vals[7..]);
Show("vals[^3..]", vals[^3..]);
Show("vals[1..^1]", vals[1..^1]);
Show("vals[..]", vals[..]);
Show("vals[4..4]", vals[4..4]);

static void Show(string label, int[] data) =>
    Console.WriteLine($"{label,-12} [{string.Join(", ", data)}]");

We take various slices of an array of ten numbers.

Show("vals[2..5]", vals[2..5]);

The range starts at index 2 and stops before index 5, so we get three elements.

Show("vals[^3..]", vals[^3..]);
Show("vals[1..^1]", vals[1..^1]);

Ranges can mix both kinds of indices. ^3.. takes the last three elements and 1..^1 drops the first and the last element.

Show("vals[4..4]", vals[4..4]);

A range whose start equals its end is empty.

$ dotnet run
vals[2..5]   [2, 3, 4]
vals[..3]    [0, 1, 2]
vals[7..]    [7, 8, 9]
vals[^3..]   [7, 8, 9]
vals[1..^1]  [1, 2, 3, 4, 5, 6, 7, 8]
vals[..]     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
vals[4..4]   []

The Index and Range types

Ranges are values that can be stored, passed to methods, and inspected.

Program.cs
Range[] ranges = [1..4, (..^2), ^3.., (..)];

foreach (var r in ranges)
{
    var (offset, length) = r.GetOffsetAndLength(10);
    Console.WriteLine($"{r,-8} start {r.Start,-3} end {r.End,-3} offset {offset}, length {length}");
}

string msg = "an old falcon";

Range middle = 3..^7;
Console.WriteLine($"[{msg[middle]}]");

Range firstWord = ..msg.IndexOf(' ');
Console.WriteLine($"[{msg[firstWord]}]");

Range all = Range.All;
Range endAt = Range.EndAt(2);
Console.WriteLine($"{all} {endAt} {Range.StartAt(^4)}");

We print the parts of several ranges and apply ranges to a string.

Range[] ranges = [1..4, (..^2), ^3.., (..)];

In a collection expression, .. at the start of an element is the spread operator. Ranges that begin with .. must therefore be put in parentheses; without them, the compiler tries to spread ^2 and reports error CS9212.

var (offset, length) = r.GetOffsetAndLength(10);

The GetOffsetAndLength method resolves a range for a collection of the given length and returns the start position and the number of elements. Note that an omitted end is stored as ^0.

Range firstWord = ..msg.IndexOf(' ');

The bounds of a range can be computed at runtime. Applying a range to a string returns a new string, the same as calling Substring.

Range all = Range.All;
Range endAt = Range.EndAt(2);

The Range struct has the static All property and the StartAt and EndAt factory methods.

$ dotnet run
1..4     start 1   end 4   offset 1, length 3
0..^2    start 0   end ^2  offset 0, length 8
^3..^0   start ^3  end ^0  offset 7, length 3
0..^0    start 0   end ^0  offset 0, length 10
[old]
[an]
0..^0 0..2 ^4..^0

Copies and views

Whether a range creates a copy depends on the type. For arrays and strings, the result is a new object. For Span<T>, ReadOnlySpan<T>, Memory<T>, and ArraySegment<T>, the result is a view of the original data.

Program.cs
int[] data = [1, 2, 3, 4, 5, 6];

int[] copy = data[1..4];
copy[0] = 100;
Console.WriteLine($"array slice:  [{string.Join(", ", data)}]");

Span<int> view = data.AsSpan()[1..4];
view[0] = 100;
Console.WriteLine($"span slice:   [{string.Join(", ", data)}]");

ArraySegment<int> segment = new(data);
ArraySegment<int> part = segment[3..];
part[0] = 400;
Console.WriteLine($"segment:      [{string.Join(", ", data)}]");

string text = "hello there";
ReadOnlySpan<char> word = text.AsSpan()[6..];
Console.WriteLine(word.ToString());

We modify slices of an array and see whether the array changes.

int[] copy = data[1..4];
copy[0] = 100;

The array slice is a copy, so the original array stays the same.

Span<int> view = data.AsSpan()[1..4];
view[0] = 100;

The span slice refers to the same memory as the array. Changing it changes the array. Slicing a span does not allocate, which matters in performance-sensitive code.

ReadOnlySpan<char> word = text.AsSpan()[6..];

The same applies to strings: text[6..] allocates a new string, while slicing a ReadOnlySpan<char> does not.

$ dotnet run
array slice:  [1, 2, 3, 4, 5, 6]
span slice:   [1, 100, 3, 4, 5, 6]
segment:      [1, 100, 3, 400, 5, 6]
there

Lists and LINQ

Indices and ranges work with more than arrays. List<T> supports both, and several LINQ methods accept them as well.

Program.cs
List<string> colors = ["red", "green", "blue", "yellow", "black"];

Console.WriteLine(colors[^1]);
Console.WriteLine(string.Join(' ', colors[1..3]));
Console.WriteLine(string.Join(' ', colors[^2..]));

colors[^1] = "white";
Console.WriteLine(string.Join(' ', colors));

var queue = new Queue<int>([1, 2, 3]);
Console.WriteLine(queue.ElementAt(^1));

var nums = Enumerable.Range(1, 10);
Console.WriteLine(string.Join(' ', nums.Take(^3..)));
Console.WriteLine(string.Join(' ', nums.Take(2..5)));

We use indices and ranges with a list, a queue, and an enumerable.

Console.WriteLine(string.Join(' ', colors[1..3]));
colors[^1] = "white";

A range applied to a list returns a new List<T>. The ^1 index can also be used for assignment.

Console.WriteLine(queue.ElementAt(^1));

A Queue<T> has no indexer. The LINQ ElementAt method accepts an Index.

Console.WriteLine(string.Join(' ', nums.Take(^3..)));

The Take method has an overload that accepts a range. It works on any IEnumerable<T>, even one whose length is not known in advance.

$ dotnet run
black
green blue
yellow black
red green blue yellow white
3
8 9 10
3 4 5

Support in custom types

A type does not need to know about Index and Range to support them. The compiler adds the support implicitly when the type is countable, that is, it has a Length or Count property, and has an int indexer for indices or a Slice(int, int) method for ranges.

Program.cs
var week = new Week();

Console.WriteLine(week[0]);
Console.WriteLine(week[^1]);
Console.WriteLine(string.Join(' ', week[1..3]));
Console.WriteLine(string.Join(' ', week[^2..]));

class Week
{
    private readonly string[] days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

    public int Length => days.Length;

    public string this[int i] => days[i];

    public string[] Slice(int start, int length) => days.AsSpan(start, length).ToArray();
}

The Week class gets indices and ranges for free.

public int Length => days.Length;

public string this[int i] => days[i];

With a Length property and an int indexer, week[^1] compiles to week[week.Length - 1].

public string[] Slice(int start, int length) => days.AsSpan(start, length).ToArray();

The Slice method takes a start position and a length. The compiler translates week[1..3] to week.Slice(1, 2).

$ dotnet run
Mon
Sun
Tue Wed
Sat Sun

Invalid ranges

A range that falls outside the collection or whose end comes before its start throws an ArgumentOutOfRangeException.

Program.cs
int[] vals = [1, 2, 3, 4, 5];

TryRange(vals, 2..10);
TryRange(vals, 4..2);
TryRange(vals, ^8..);
TryRange(vals, 5..);

static void TryRange(int[] arr, Range r)
{
    try
    {
        int[] part = arr[r];
        Console.WriteLine($"{r}: [{string.Join(", ", part)}]");
    }
    catch (ArgumentOutOfRangeException e)
    {
        Console.WriteLine($"{r}: {e.GetType().Name}");
    }
}

We apply several ranges to an array of five elements.

TryRange(vals, 2..10);
TryRange(vals, 4..2);
TryRange(vals, ^8..);
TryRange(vals, 5..);

The first range ends past the array, the second one runs backwards, and the third one starts before the beginning. Unlike some other languages, C# does not clamp the bounds. The last range starts exactly at the end of the array, which is allowed and returns an empty array.

$ dotnet run
2..10: ArgumentOutOfRangeException
4..2: ArgumentOutOfRangeException
^8..^0: ArgumentOutOfRangeException
5..^0: []

Source

Index from end operator ^

Range operator ..

In this article we have worked with ranges and indices in C#. See also the array, Span, ArraySegment, and indexers tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.