What are indices and ranges in C# 8.0?
In C# 8.0, additional support was added to facilitate array indexing. The new syntax is easier to use and more intuitive to understand.
Indices
In previous versions of C#, we access an array element as follows, given that its index is known:
//months is the array name
//1 is the known index
Console.WriteLine(months[1]);
When the array length and index are unknown, we use the array.Length function to access an array element, given that we know its position from the last index:
//months.Length function returns the length of the array, and we use it to access the second last element
Console.WriteLine(months[months.Length-2])
In C# 8.0, a variable of type Index can be defined instead and used as the array index. In the example below, the variable of type Index starts counting from the start:
Index ind=5;
Console.WriteLine(months[ind]);
To access the second to last index of an array in C# 8.0, we can alter the functionality of the Index variable by inserting the ^ operator. Now, the variable of type Index will start counting from the end:
//accesses second element from the end
Index ind=^2;
Console.WriteLine(months[ind]);
Ranges
Similarly, to access a range of values, we can use the .. range operator, introduced in C# 8.0.
The start (inclusive) and end (exclusive) indices are to be provided before and after the .. operator, respectively.
The following snippet demonstrates how to extract a substring that starts from the 2nd index and ends at the 5th index of the original array:
string [] sample=months[2..6];
We can use the ^ operator in ranges as well:
// stores the second last, and last elements of months in sample
string [] sample=months[^2..^0];
Free Resources