16

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?

Pang
  • 9,564
  • 146
  • 81
  • 122
Hamed Naeemaei
  • 8,052
  • 3
  • 37
  • 46
  • 4
    https://blog.cdemi.io/whats-coming-in-c-8-0-ranges-and-indices/ – canton7 Mar 14 '19 at 16:13
  • I can recomment this for a short intro (section Index and Range): https://devblogs.microsoft.com/dotnet/announcing-net-core-3-preview-3 – kapsiR Mar 14 '19 at 16:18

2 Answers2

19

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);
Pang
  • 9,564
  • 146
  • 81
  • 122
Magnetron
  • 7,495
  • 1
  • 25
  • 41
  • 2
    So Index from end are 1 based and Range from end are 0 based? That's confusing. – Maxter May 22 '19 at 18:37
  • Does `"abc"[0..1]` alloc new string? – huang Apr 17 '20 at 06:42
  • 7
    @Maxter It's better to think of indexes as referring to the gaps between characters. 0 is before the first character; 1 is between first and second, ^1 is between second-to-last and last, and ^0 is after the last. Ranges always select the characters between the two gaps. Accessing a single element always gives you the element after the gap. – Daniel Apr 22 '20 at 13:42
  • Thx Daniel, this actually helped. – Maxter Apr 24 '20 at 14:18
0

System.Index Excellent way toindex a collection from the ending. (Which can be used to obtain the collection from the beginning or from the end).

System.Range Ranges way to access "ranges" or "slices" of collections. This will help you to avoid LINQ and making your code compact and more readable. (Access a sub-collection(slice) from a collection).

More Info in my articles:

https://www.c-sharpcorner.com/article/c-sharp-8-features/

https://www.infoq.com/articles/cs8-ranges-and-recursive-patterns

Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70