Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Index" and "range" operators - what are they?

I was adjusting code style settings for C# and I noticed these options:

"Prefer index operator:"

// Prefer:
var ch = value[^1];

// Over:
var ch = value[value.Length - 1];

"Prefer range operator:"

// Prefer:
var sub = value[1..^1];

// Over:
var sub = value.Substring(1, value.Length - 2);

I'm struggling to find any reference on these. What does "index operator" and "range operator" mean in this case? How do you use them?

like image 493
KainDefiant Avatar asked Nov 21 '25 00:11

KainDefiant


1 Answers

I guess the main advantage of using index and range operators is their simplicity.

Index Operator ^

Index operator ^ means from the end. Consequently, array[^1] means first element from the end. It is analogous to the common indexing, array[1] means one element from the start. The index ^0 means the end.

Range Operator ..

As you have shown in your example above, it is much convenient to create substring using range operator. Range operator can be used to create subarrays as well. For example,
var array = new {1, 2, 3, 4, 5, 6, 7}; var range = array[2..5]
Here's Microsoft documentation for the above topics: Indices and ranges

like image 111
Gray_Rhino Avatar answered Nov 22 '25 15:11

Gray_Rhino