Proposal: Fully Inclusive Ranges #6573
Unanswered
colejohnson66
asked this question in
Language Ideas
Replies: 2 comments 6 replies
-
There was a discussion a while back about considering additional notation for representing inclusivity/exclusivity but there was little interest in the idea. |
Beta Was this translation helpful? Give feedback.
6 replies
-
Tadpole operator? 0..~-10 // 0..9
0..-~10 // 0..11 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Background
C#'s ranges can only be
[start, end)
(inclusive start, exclusive end). This is a bit limiting.For example, I have some code that can extract a
Range
of bits from a number:If I'm using said code to implement a bitfield and I wanted to get the field at bits 12 and 13 of the backing number, I actually have to pass a range of
12..14
:Any experienced C# programmer will understand that the above statement will only get 2 bits (
14 - 12 == 2
), but it requires extra thought that could be avoided.On the other hand, Rust's ranges can be fully inclusive and would allow me to write:
I propose C# support the same.
Proposal
This would be implemented as syntax sugar on top of the existing
Range
syntax:The compiler and JIT would perform constant folding as necessary.
Open-ended ranges (i.e.
..=
anda..=
) would be illegal with this new syntax, asa..=
would have whatever nonsensical valueIndex.End + 1
would be.The "from end" syntax would need discussion. There are three possible options for what
..=^a
would mean:..=^(a+1)
..=^(a-1)
(from..=(~a+1)
)The first would mean
stc[..=^1]
(desugared assrc[..^2]
) follows what some people's expectation of ranges is ("one from end means all but the last"), not what is currently is. The second would meansrc[..=^1]
(desugared assrc[..^0]
) causes an exception when slicing. The final option is to just make it illegal and avoid any confusion.Beta Was this translation helpful? Give feedback.
All reactions