Until now, if you wanted to access the last item in a list you had to use a slightly cumbersome syntax. C# 13 introduces the “hat” operator (^) where ^1 is the last element in your collection, ^2 is the penultimate member, etc.
Like many things, this is best illustrated with an example. In the following code I create a simple Person class and initialize a list<Person> with three people (persons?)
internal class Program
{
static void Main(string[] args)
{
var tester = new Tester();
tester.Test();
}
}
public class Tester()
{
public void Test()
{
var john = new Person { Name = "John", Age = 25 };
var jane = new Person { Name = "Jane", Age = 30 };
var joe = new Person { Name = "Joe", Age = 35 };
var people = new List<Person> { john, jane, joe };
}
}
public class Person()
{
public string Name { get; set; }
public int Age { get; set; }
}
Straight forward. Now, if I want to access the last person in this list I can write
var lastPerson = people[^1];
Console.WriteLine($"Last person is {lastPerson.Name} who is {lastPerson.Age} years old.");
As you can see, this is concise and easy to understand. You read it as “lastPerson is equal to one back from the end of people.” Let’s run it:
Last person is Joe who is 35 years old.
That is all there is to it. Easy to use and somewhat helpful in simplifying your code.