Modern C# Part 2 – Accessing via Implicit Index

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.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *