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]); // 10The ^ (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]); // 40All lessons in this course
- The Index Type and ^ Operator
- The Range Type and .. Operator
- Ranges with Arrays and Strings
- Custom Types Supporting Ranges