Get the last item in a C# collection

When a collection keeps its newest value at the end, C# lets you read that value with index-from-end notation:

var names = new List<string>
{
    "Ada",
    "Grace",
    "Linus"
};

string lastName = names[^1];

^1 means “the first item counted from the end.” Therefore, names[^1] gets the last item, names[^2] gets the item before it, and so on. The notation is available for arrays and collections that support the relevant indexer, including List<T>.

The traditional index calculation

Before index-from-end notation, code commonly calculated the last zero-based index explicitly. Arrays use Length:

var scores = new[] { 72, 85, 91 };
int lastScore = scores[scores.Length - 1];

List<T> uses Count, not Length:

var scores = new List<int> { 72, 85, 91 };
int lastScore = scores[scores.Count - 1];

Both forms select the same item. ^1 is often easier to read because it says directly that the code wants the last item.

Guard against an empty collection

There is no last item in an empty array or list. Check the collection before using either form so the program does not throw an IndexOutOfRangeException or ArgumentOutOfRangeException:

if (names.Count > 0)
{
    string lastName = names[^1];
    Console.WriteLine(lastName);
}

For an array, use scores.Length > 0 in the guard. If you want to handle an empty collection with a fallback value, LastOrDefault() from LINQ is another option; remember to handle its default result when the element type can be null.