Tip #016
The ^ index operator
About this tip
^n counts from the end: ^1 is the last item. Skip numbers[numbers.Length - 1]. It is available since C# 8. The key line is var last = numbers[^1] in index.cs. It fits in 9 lines; run it with dotnet run index.cs.
Learn more
Did this tip save you some time? Consider buying me a coffee to fuel the next one.
Buy me a coffee
Railway
Referral
Need somewhere to deploy?
My link gets you $20 in credits.
Claim $20 creditI may earn a commission if you become a customer.
Code
int[] numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var first = numbers[0];var last = numbers[^1];var second = numbers[^2];
Console.WriteLine(first);Console.WriteLine(last);Console.WriteLine(second);Output
$ dotnet run index.cs198