C# / Unity Tip: Get the index from end of an array or list

So, I was in the midst of developing my game when I wanted to retrieve the penultimate (I looked it up, it exists) member of my pathfinding array to determine if the point before the ULTIMATE target is reachable. So, naturally, I used the old self-referencing line to get the work done and created a static method to do the job.

C#
        ...PathExtensions.GetPositionOnPath(path, path.vectorPath.Count -2)...        
        
        /// Method to retrieve the index from the end
        
        public static Vector3 GetPositionOnPath(Path path, int i)
        {
            return path.vectorPath[i];
        }

But wait! Something in the deeper parts of my brain itched. There was some other way to achieve this much more elegantly. And yes, I was right! Again!

INTRODUCING THE ^_____^

After a quick Google search, I found the answer. With C# 8.0 and later, you can indeed use the caret symbol (^) to index arrays, which is known as the “index from end” feature. Nice! It is now much more readable and easier to maintain.

C#
        ...PathExtensions.GetPositionOnPath(path,^2)...
        
        /// Much simpler method to retrieve the index from the end
        
        public static Vector3 GetPositionOnPath(Path path, Index i)
        {
            return path.vectorPath[i];
        }

Some examples:

C#
        string[] colors = { "red", "blue", "green", "yellow", "orange", "purple", "pink", "brown", "black", "white" };

        // Accessing the last element of the array:
        Debug.Log(colors[^1]);
        // Output: "white"

        // Accessing the second to last element of the array:
        Debug.Log(colors[^2]);
        // Output: "black"

        // Accessing the third element of the array:
        Debug.Log(colors[^3]);
        // Output: "brown"

        // Accessing the first element of the array:
        Debug.Log(colors[^10]);
        // Output: "red"

Hope that helps! Bye.

Official documentation:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#index-from-end-operator-

Leave a Comment