0Pricing
C# Academy · Lesson

The Index Type and ^ Operator

Reference elements from the end of a collection.

Meet the Index Type

C# gives you a dedicated System.Index type to describe a position inside a sequence. Unlike a plain int, an Index can represent a position counted from the end of a collection, not just from the start.

This makes code like "give me the last element" expressive and safe.

using System;

int[] numbers = { 10, 20, 30, 40, 50 };
Index first = 0;
Console.WriteLine(numbers[first]); // 10

The ^ (from-end) Operator

The hat operator ^ builds an Index that counts from the end. ^1 means the last element, ^2 the second-to-last, and so on.

Note that ^1 is the last valid index, while ^0 equals Length and is one past the end.

using System;

int[] numbers = { 10, 20, 30, 40, 50 };
Console.WriteLine(numbers[^1]); // 50 (last)
Console.WriteLine(numbers[^2]); // 40

All lessons in this course

  1. The Index Type and ^ Operator
  2. The Range Type and .. Operator
  3. Ranges with Arrays and Strings
  4. Custom Types Supporting Ranges
← Back to C# Academy