How to use ranges in C# – C# 8

 Maybe the range term would be familiar to you but many developers out there are not using it.

Ranges and indices are the easiest and most efficient way to access items from a collection.

This is quite an immense feature of C#8.

C# 8 added a new feature called “ranges” that enables developers to work with ranges of elements in arrays, lists, and other collection types. The range feature consists of two new types, Range and Index, as well as a set of new operators that make working with ranges simple.

Here are some examples of using ranges in C# 8:

  • Use the.. operator to construct a range of elements in an array. For example, to obtain the entries in an array from index 2 to index 4, use the following code:

int[] numbers = { 1, 2, 3, 4, 5 };

int[] subArray = numbers[2..4];

  • To create a range that starts at a specific index and goes to the end of the array, use the ^ operator. For example, to get all elements from index 2 to the end of an array, you can use the following code:
int[] numbers = { 1, 2, 3, 4, 5 };
int[] subArray = numbers[2..^0];
  • To create a range that starts at the beginning of an array and goes to a specific index, use the ..^ operator. For example, to get all elements from the beginning of an array to index 2, you can use the following code:
int[] numbers = { 1, 2, 3, 4, 5 };
int[] subArray = numbers[..^2];
  • To create a range that starts from a specific index and goes to the end of the array using Index type:
int[] numbers = { 1, 2, 3, 4, 5 };
Index index = 2;
int[] subArray = numbers[index..];
  • To create a range that starts from the beginning of the array and goes to a specific index using Index type:
int[] numbers = { 1, 2, 3, 4, 5 };
Index index = 2;
int[] subArray = numbers[..index];
 
 
It’s important to note that the above examples are only for illustration purposes and the code may need to be adjusted depending on the context and use case.

Leave a Reply

Your email address will not be published. Required fields are marked *