Ranges

suggest change

Introduced in C# 8.0, indices and ranges provide a concise syntax for accessing single elements or continuous subsets (slices) of a sequence. They are backed by the System.Index and System.Range types and supported natively by arrays, strings, Span<T>, ReadOnlySpan<T>, and custom types that implement the slicing pattern.

The Index Type and From-End Operator (^)

The System.Index structure represents an offset into a sequence, which can be measured either from the start (0-based) or from the end using the index-from-end operator (^).

string[] languages = ["C#", "F#", "TypeScript", "Rust", "Go"];

// Normal 0-based indexing from the beginning:
string first = languages[0]; // "C#"

// Using the ^ operator to index from the end:
// ^1 is the last element; ^languages.Length is the first element
string last = languages[^1];        // "Go"
string secondToLast = languages[^2]; // "Rust"

// Creating an Index explicitly:
Index indexFromEnd = new Index(value: 3, fromEnd: true);
string thirdFromEnd = languages[indexFromEnd]; // "TypeScript"

[!NOTE] ^0 corresponds to languages.Length. Because indexing is zero-based, languages[^0] throws an IndexOutOfRangeException, exactly as languages[languages.Length] does.

The Range Type and Slicing Operator (..)

The System.Range structure represents a start index and an end index. The range operator .. specifies a sub-range that is inclusive of the start index and exclusive of the end index ([start, end)).

int[] numbers = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90];

// Slice from index 2 up to, but not including, index 6
int[] middle = numbers[2..6]; // [20, 30, 40, 50]

// Mix start-based and end-based indices:
int[] inner = numbers[1..^1]; // [10, 20, 30, 40, 50, 60, 70, 80]

// Open-ended ranges:
int[] firstThree = numbers[..3];   // Equivalent to 0..3: [0, 10, 20]
int[] fromFourOn = numbers[4..];   // From index 4 to end: [40, 50, 60, 70, 80, 90]
int[] allElements = numbers[..];   // A shallow copy of all elements

// Storing a Range in a variable:
Range targetRange = 3..^2;
int[] subset = numbers[targetRange]; // [30, 40, 50, 60, 70]

Slicing Strings

Strings support indices and ranges directly. Slicing a string returns a new substring:

string filename = "report-2026-q3.json";

// Extract extension
string extension = filename[^5..]; // ".json"

// Extract year
string year = filename[7..11]; // "2026"

// Extract base name without extension
string baseName = filename[..^5]; // "report-2026-q3"

Memory and Performance: Array vs. Span<T>

When you slice an array (array[1..4]) or a string (str[1..4]), the runtime allocates a new array or string containing the copied data.

To slice collections without heap allocations, use Span<T> or ReadOnlySpan<T>:

ReadOnlySpan<int> span = numbers.AsSpan();

// Zero-allocation slicing
ReadOnlySpan<int> slice = span[2..6];

// String slicing without heap allocations
ReadOnlySpan<char> textSpan = filename.AsSpan();
ReadOnlySpan<char> extSpan = textSpan[^5..];
bool isJson = extSpan.SequenceEqual(".json");

Enabling Range Support in Custom Types

A custom class or struct can participate in range and index syntax without implementing an interface. The C# compiler recognizes the pattern if your type exposes:

  1. An int Length or int Count property.
  2. An indexer taking an int, or an indexer taking Index.
  3. A Slice(int start, int length) method, or an indexer taking Range.
public class BufferWindow<T>
{
    private readonly T[] _items;

    public BufferWindow(T[] items) => _items = items;

    public int Length => _items.Length;

    public T this[int index] => _items[index];

    // Method pattern recognized by compiler for range expressions:
    public BufferWindow<T> Slice(int start, int length)
    {
        T[] slice = new T[length];
        Array.Copy(_items, start, slice, 0, length);
        return new BufferWindow<T>(slice);
    }
}

// Usage:
var window = new BufferWindow<string>(["alpha", "bravo", "charlie", "delta"]);
BufferWindow<string> middleSlice = window[1..^1]; // "bravo", "charlie"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents