Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.Index and System.Range — indices and slices

System.Index describes a position measured from the start or end of a sequence, while System.Range describes a start-inclusive, end-exclusive interval. The ^ and .. operators simplify element access and slicing; cost and data sharing depend on the sequence type.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

Index last = ^1; Range middle = 1..^1; var item = sequence[last]; var slice = sequence[middle];

System.Index and System.Range are immutable value types supporting indexing and slicing since C# 8. They are available in .NET 10; the repository setting LangVersion=preview is not required for this feature. They store descriptions of positions or intervals, not the sequence itself or its elements.

Index stores Value and IsFromEnd. An ordinary nonnegative int implicitly converts to a from-start index. ^n means position Length - n: ^1 identifies the last element of a nonempty sequence, whereas ^0 is the past-end boundary. Therefore, values[^0] throws. A negative value passed to the Index constructor or conversion from int causes ArgumentOutOfRangeException. GetOffset(length) calculates an offset but does not check whether it identifies an existing element.

Range contains the indices Start and End. The expression a..b includes the start but excludes the end; 1..^1 omits the first and last elements. Omitted boundaries default to 0 and ^0: ..b, a.., and ... GetOffsetAndLength(length) returns an offset and element count. It throws ArgumentOutOfRangeException if the boundaries fall outside 0..length or the start falls after the end. Equal boundaries describe an empty slice, not a reversed interval.

Single-dimensional arrays, string, Span<T>, and ReadOnlySpan<T> support this syntax. Merely implementing IEnumerable<T> is insufficient: suitable indexers or a compiler-recognized pattern are needed. An array slice creates a shallow copy of the elements; objects referenced by reference-type elements can still be shared. A Span<T> or ReadOnlySpan<T> slice is a view over the same memory, without copying elements.

Examples

using System;

internal static class Program
{
    private static void Main()
    {
        int[] values = { 10, 20, 30, 40, 50 };
        Index last = ^1;
        Range middle = 1..^1;
        int[] copy = values[middle];
        copy[0] = 99;

        Console.WriteLine(values[last]);
        Console.WriteLine(string.Join(",", copy));
        Console.WriteLine(values[1]);
        var (offset, length) = middle.GetOffsetAndLength(values.Length);
        Console.WriteLine($"{offset}:{length}");
    }
}

Result

50
99,30,40
20
1:3

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources