How to use indices and ranges in C#

By FoxLearn 1/3/2025 3:09:54 AM   79
In C# 8.0, two important new features, System.Index and System.Range, have been introduced to simplify indexing and slicing operations for collections.

These structures make it easier to access elements from the start or end of a collection and extract subsets of data.

Use System.Index in C# 8.0 to index a collection from the end

The System.Index struct is used for indexing, and it allows you to reference elements from the end of a collection using the ^ operator. This eliminates the need to manually calculate indices when accessing elements from the end.

int[] numbers = { 10, 20, 30, 40, 50, 60, 70 };
var lastNumber = numbers[^1]; // Retrieves the last element, 70
Console.WriteLine("The last number is: " + lastNumber);

In this case, the output will be The last number is: 70.

Use System.Range in C# 8.0 to extract the subset of a sequence

The System.Range struct allows you to extract a slice or range of elements from a collection. You can specify the start and end points of the slice.

For example, if you wanted to extract a part of a string:

string phrase = "Learning C# is fun!";
Console.WriteLine(phrase[10..]); // Output: "is fun!"

This code uses the Range to grab the substring starting from the 10th index to the end of the string.

Similarly, you can slice an array.

For instance, to extract a subarray from an integer array:

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var rangeSlice = numbers[3..6]; // Extracts elements from index 3 to 5 (4, 5, 6)
foreach (int num in rangeSlice)
    Console.WriteLine(num);

This will print:

4
5
6

You can also use ranges with different starting and ending points.

For example, to extract the first three elements from an array:

string[] colors = { "Red", "Green", "Blue", "Yellow", "Purple" };
var colorSlice = colors[..3]; // Extracts the first three elements
foreach (var color in colorSlice)
{
    Console.WriteLine(color);
}

This outputs:

Red
Green
Blue

Before C# 8.0, there was no easy way to slice collections or access elements from the end. The new ^ operator and .. range operator introduced in C# 8.0 provide a more concise, readable, and maintainable way to perform these operations, making code cleaner and more efficient.