Code4IT

The place for .NET enthusiasts, Azure lovers, and backend developers

C# Tip: Access items from the end of the array using the ^ operator

2023-04-11 2 min read CSharp Tips
Just a second!
If you are here, it means that you are a software developer. So, you know that storage, networking, and domain management have a cost .

If you want to support this blog, please ensure that you have disabled the adblocker for this site. I configured Google AdSense to show as few ADS as possible - I don't want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

Thank you for your understanding.
- Davide

Say that you have an array of N items and you need to access an element counting from the end of the collection.

Usually, we tend to use the Length property of the array, and then subtract the number corresponding to the position we want to reach:

string[] values = {
    "alfa",
    "bravo",
    "charlie",
    "delta",
    "echo",
    "foxtrot",
    "golf"
};

var echo = values[values.Length - 3];

As you can see, we are accessing the same variable twice in a row: values[values.Length - 3].

We can simplify that specific line of code by using the ^ operator:

string[] values = {
    "alfa",
    "bravo",
    "charlie",
    "delta",
    "echo",
    "foxtrot",
    "golf"
};

var echo = values[^3];

Yes, that’s just syntactic sugar, but it can help make your code more readable. In fact, if you have a look at the IL code generated by both examples, they are perfectly identical. IL is quite difficult to read and understand, but you can acknowledge that both syntaxes are equivalent by looking at the decompiled C# code:

C# decompiled code

Performance is not affected by this operator, so it’s just a matter of readability.

Clearly, you still have to take care of array bounds - if you access values[^55] you’ll get an IndexOutOfRangeException.

Pay attention that the position is 1-based!

string[] values = {
    "alfa",
    "bravo",
    "charlie",
    "delta",
    "echo",
    "foxtrot",
    "golf"
};

Console.WriteLine(values[^1]); //golf
Console.WriteLine(values[^0]); //IndexOutOfRangeException

Further readings

Using ^ is a nice trick that many C# developers don’t know. There are some special characters that can help us but are often not used. Like the @ operator!

🔗 C# Tip: use the @ prefix when a name is reserved

This article first appeared on Code4IT 🐧

Wrapping up

In this article, we’ve learned that just using the right syntax can make our code much more readable.

But we also learned that not every new addition in the language brings performance improvements to the table.

I hope you enjoyed this article! Let’s keep in touch on Twitter or on LinkedIn, if you want! 🤜🤛

Happy coding!

🐧