Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are Range and Index types in C# 8?

Tags:

c#

c#-8.0

In C# 8, two new types are added to the System namespace: System.Index and System.Range.

How do they work and when can we use them?

like image 998
Hamed Naeemaei Avatar asked Mar 14 '19 16:03

Hamed Naeemaei


People also ask

What is index in range?

A range index is a variant of an inverted index, where instead of creating a mapping from values to columns, we create mapping of a range of values to columns. You can use the range index by setting the following config in the table config. { "tableIndexConfig": { "rangeIndexColumns": [

What is the index range of an array?

An extent: this is the range of the indices or subscripts of array elements. For example, the range of an array can be 1 to 10 (i.e., elements 1, element 2, elements 3, ..., element 10) or -3 to 5 (i.e., element -3, element -2, ..., element 4, element 5). Indices or subscripts must be integers within the range.

What is a range operator?

The range operator is used as a shorthand way to set up arrays. When used with arrays, the range operator simplifies the process of creating arrays with contiguous sequences of numbers and letters. We'll start with an array of the numbers one through ten.

What is index operator in C#?

In C# the ^ operator means index-from-the-end while in regex the character ^ matches the starting position within the string.


1 Answers

They're used for indexing and slicing. From Microsoft's blog:

Indexing:

Index i1 = 3;  // number 3 from beginning
Index i2 = ^4; // number 4 from end
int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Console.WriteLine($"{a[i1]}, {a[i2]}"); // "3, 6"

Range (slicing):

We’re also introducing a Range type, which consists of two Indexes, one for the start and one for the end, and can be written with a x..y range expression. You can then index with a Range in order to produce a slice:

var slice = a[i1..i2]; // { 3, 4, 5 }

You can use them in Array, String, [ReadOnly]Span and [ReadOnly]Memory types, so you have another way to make substrings:

string input = "This a test of Ranges!";
string output = input[^7..^1];
Console.WriteLine(output); //Output: Ranges

You can also omit the first or last Index of a Range:

output = input[^7..]; //Equivalent of input[^7..^0]
Console.WriteLine(output); //Output: Ranges!

output = input[..^1]; //Equivalent of input[0..^1]
Console.WriteLine(output); //Output: This a test of Ranges

You can also save ranges to variables and use them later:

Range r = 0..^1;
output = input[r];
Console.WriteLine(output);
like image 63
Magnetron Avatar answered Oct 13 '22 14:10

Magnetron