C# 8 added the ranges syntax to C#:
var slice = myArray[0..2];
What I find not so intuitive is that the upper bound (2
in the previous example) is exclusive - not inclusive; i.e. myArray[0..2]
returns a slice with 2 elements (0 and 1), not with 3 elements.
So my question is: Why did the C# language designers choose to make the upper bound exclusive?
Both the ranges documentation as well as the design champion issue simply state that the upper bound is exclusive - without giving any explanation as to why (at least none that I could find). There also was a discussion about this on GitHub but it also doesn't seem to contain any official explanation.
By searching StackOverflow I stumbled across the same question for Python. Python also treats the upper bound as exclusive. So I can imagine that the C# language designers were looking at other languages (that have ranges) and were trying to make C#'s behavior consistent with other languages. But I'm still wondering if there is any official documentation on this decision.
There are a lot of design decisions that just won't have satisfying answers. However, this one at least has a paper-trail you can follow in the design notes (in one or more mentions) starting at the following link.
Note : This was just an arbitrary decision, the reason they chose exclusive is because they chose exclusive. It could easily not have been the case due to the pros and cons.
C# Language Design Notes for Jan 22, 2018
...
Conclusion
Let us go with
..
means exclusive. Since we've chosen to focus on the indexing/slicing scenario, this seems the right thing to do:
- It allows
a.Length
as an endpoint without adding/subtracting 1.- It lets the end of one range be the beginning of the next without overlap
- It avoids ugly empty ranges of the form
x..x-1
And as @vc74 mentions in the comments and also stated in the document supplied, other languages like Python follow this convention, however others don't.
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