Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 182 ยท Operators and Control Flow

Ranges and Indices

Learn C# index-from-end (^1) and range (1..3) syntax, the Index and Range types, slicing arrays, strings and spans, and how to make your own types support ranges.

Taking the last element of an array used to mean writing array[array.Length - 1]. Taking the middle part of a string meant counting characters for Substring. C# 8 introduced a much shorter notation for both: array[^1] for "one from the end" and array[1..4] for "from position 1 up to (not including) position 4". These are the index and range operators.

This lesson explains how the notation works, how it maps onto the System.Index and System.Range types, what is copied and what is not when you slice (arrays copy, spans do not), which built-in types support ranges, and how to add range support to your own types. It builds on arrays and strings, and on what you learned about loops.

Counting from the end: ^

A normal index counts from the front: 0 is the first element. The hat operator ^ counts from the end: ^1 is the last element, ^2 the second to last, and so on. Note that ^1 (not ^0) is the last one, because ^0 means "one past the end", which is the same as Length.

C# Indexing from the end

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.

The expression planets[^2] is translated by the compiler into planets[planets.Length - 2], so it costs nothing extra at run time. If the position is out of bounds you get the usual IndexOutOfRangeException; for instance planets[^6] on a five-element array fails because it means index -1.

The Index type

The ^n notation creates a value of the struct System.Index. You can store it in a variable, pass it around, and ask whether it counts from the end:

C# Index values

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.

An int converts implicitly to an Index (counting from the front), which is why Index first = 0; compiles. GetOffset(length) turns the index into an ordinary position for a collection of that length, here 3.

Slicing with ranges: ..

A range start..end selects the elements from start up to but not including end. Both ends are indexes and may use ^. Either end can be left out: a missing start means 0, a missing end means ^0, the end of the collection.

C# Range forms on an array

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.

The result of the third line is 7,8,9, the fourth is 7,8,9 too, and n[5..5] has length 0: a range whose start equals its end is simply empty, not an error. Because the end is exclusive, the length of a..b is always b - a, which makes ranges easy to reason about. A start after the end, like n[5..3], throws ArgumentOutOfRangeException.

The end is exclusive in every half-open range in C#, the same convention as for (int i = 0; i < n; i++). Writing n[2..5] selects three elements.

The Range type

Like Index, a range is a value: System.Range holds two Index values (Start and End).

C# Range values

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.

Storing ranges is useful for configuration (which columns to show), for parsing code that remembers where tokens were found, and for passing a slice description to a method. Range.All equals 0..^0.

What is copied? Arrays versus strings versus spans

The notation looks the same everywhere, but the cost depends on the type.

Type x[1..3] returns Copies data?
T[] new T[] Yes (RuntimeHelpers.GetSubArray)
string new string Yes (same as Substring)
Span<T>, ReadOnlySpan<T> a span over the same memory No
List<T> new List<T> (via its Slice method) Yes

So slicing a large array in a loop allocates a new array each time. When performance matters, slice a span instead:

C# Copy versus view

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.

The copy leaves data untouched (1,2,3,4,5,6), while writing through the span changes the original (1,99,3,4,5,6). Spans are explained in spans and memory.

Strings

text[a..b] on a string is equivalent to text.Substring(a, b - a), with the same copying:

C# Slicing strings

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.

word[0] == word[^1] compares the first and last characters, which is the heart of a palindrome check without any Length - 1 arithmetic. Remember that strings are UTF-16: ranges select char code units, so an emoji made of a surrogate pair can be cut in half. See strings for that caveat.

Which types support indexes and ranges?

C# does not hard-code the list of types. It uses pattern-based rules, so any type that follows the right shape works, including your own.

  • Index (^n): supported by a type that is countable (it has an int Length or int Count property) and has an accessible int indexer. T[], string, Span<T> and List<T> all qualify.
  • Range (a..b): supported by a countable type that has a Slice(int start, int length) method, or an indexer that takes a Range parameter. Arrays and strings are special-cased by the compiler.

List<T> follows the pattern too: it has a Count, an int indexer and a public Slice(int, int) method, so both list[^1] and list[1..3] work, and the range version returns a new List<T> with copied elements.

C# Lists support ^ and ranges

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.

The slice is a copy: changing part leaves list alone. For collections that do not follow the pattern, such as HashSet<T> (no indexer) or a plain IEnumerable<T>, use LINQ's Skip and Take, or the Take(Range) overload shown below.

Adding range support to your own type

If your type has Count (or Length), an int indexer and a Slice(int, int) method, both ^ and .. work automatically. The compiler rewrites x[a..b] into x.Slice(start, length).

C# A type with Count, an indexer and Slice

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.

When the compiler sees playlist[1..^1], it calls playlist.Count once, converts the range into start = 1 and length = Count - 2, and calls playlist.Slice(1, Count - 2). For playlist[^1] it computes the index Count - 1 and calls the int indexer. No interface is needed.

If you would rather control everything yourself, give the type indexers that take Index or Range directly:

C# Indexers taking Index and Range

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.

Because the class declares indexers with Index and Range parameters, the compiler uses them directly. Both approaches are valid; the pattern-based one (Count + indexer + Slice) is simpler for sequence-like types.

Ranges in other places

  • LINQ and slicing. For collections without range support, Skip(a).Take(b - a) does the same thing.
  • Pattern matching. List patterns use .. to mean "any number of elements": [var first, .., var last].
  • Enumerable.Take(Range). Since .NET 6 you can write source.Take(2..4) and source.Take(^3..) for sequences, which enumerates the source to find the length when it needs one.
  • Late errors. An index such as ^9 is valid to create; the exception comes only when it is used on a collection that is too short.
C# Take with ranges on a sequence

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.

Common mistakes

  • Thinking ^0 is the last element. ^1 is the last; ^0 equals Length and throws when used as an element index.
  • Forgetting the end is exclusive. array[0..3] has three elements, not four.
  • Slicing arrays in a hot loop. Each slice allocates; use AsSpan() instead.
  • Slicing strings by char in Unicode text. You can split surrogate pairs or combining sequences.
  • Expecting a slice to share memory. Ranges on arrays, strings and lists copy; only spans give a view.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given int[] a = [5, 6, 7, 8], what is a[^2]?

    ^1 is the last element (8) and ^2 the one before it (7).
  2. 2. How many elements does array[2..6] contain?

    The end of a range is exclusive, so 2..6 selects positions 2, 3, 4 and 5: four elements (6 - 2).
  3. 3. What does data.AsSpan()[1..4] do differently from data[1..4] when data is an int[]?

    Slicing an array allocates a new array, but slicing a span returns another span pointing into the same memory.
  4. 4. Which members allow a custom class to support x[1..3] automatically?

    The compiler uses a pattern: a countable type with an int indexer and a Slice(int start, int length) method.
  5. 5. What is the type of the expression ^1?

    The hat operator produces a System.Index. The .. operator produces a System.Range built from two Index values.

Summary

  • ^n counts from the end: ^1 is the last element and ^0 is one past it.
  • start..end selects from start up to but not including end; either end can be omitted.
  • ^n creates a System.Index, a..b creates a System.Range; both are values you can store and pass.
  • Slicing arrays and strings copies data; slicing Span<T> and ReadOnlySpan<T> does not.
  • A type supports ^ with Count/Length plus an int indexer, and supports .. with a Slice(int, int) method or a Range indexer.
  • List<T> supports both ^ and .. (the slice is a copy); sequences without an indexer need LINQ or Take(Range).

Next: Pattern Matching Basics