int []arr = new int[4];
arr[^1]; // returns the last element
I'm trying to figure out the syntax above. It's returning the last element, but why?
int []arr = new int[4];
arr[^1]; // returns the last element
I'm trying to figure out the syntax above. It's returning the last element, but why?
C# 8.0 and going forward, declared the new ranges and indexes
Among them the ^
operator:
Let's start with the rules for indices. Consider an array sequence. The
0
index is the same assequence[0]
. The^0
index is the same assequence[sequence.Length]
.
So it a way to search an indexable object in reverse, without needing to iterate like sequence[sequence.Length - i]
.
string[] words = new string[]
{
// index from start index from end
"The", // 0 ^9
"quick", // 1 ^8
"brown", // 2 ^7
"fox", // 3 ^6
"jumped", // 4 ^5
"over", // 5 ^4
"the", // 6 ^3
"lazy", // 7 ^2
"dog" // 8 ^1
}; // 9 (or words.Length) ^0