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?
I guess the main advantage of using index and range operators is their simplicity.
^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.
..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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With