- #80293
-
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Moving to runtime. This is not a lang issue. |
Beta Was this translation helpful? Give feedback.
-
Original topic: foreach (var x in 1 .. 10)
{
Console.WriteLine(x);
} Try and write the above code and one gets:
Many have asked, why doesn't Range implement IEnumerable and the reason given - as I understand it - is because of "from end" ranges. What is the following supposed to do? foreach (var x in ^1 .. ^10)
{
Console.WriteLine(x);
} So because of this, Range doesn't implement IEnumerable. Now I'll concur that the ^1 at the start of the range doesn't make much sense. But that ^10 is actually useful. Consider what we might expect the output of this code to be: foreach (var x in 1 .. 10)
{
Console.Write($"{x} ");
}
Console.WriteLine(); I'm assuming most people will be like me here and expect foreach (var x in 1 .. ^10)
{
Console.Write($"{x} ");
}
Console.WriteLine(); would output And of course we can easily do reverse ranges too: # Outputs 10 9 8 7 6 5 4 3 2
foreach (var x in 10 .. 1)
{
Console.Write($"{x} ");
}
Console.WriteLine();
# Outputs 10 9 8 7 6 5 4 3 2 1
foreach (var x in 10 .. ^1)
{
Console.Write($"{x} ");
}
Console.WriteLine(); To my mind, the usefulness of being able to so succinctly express incremental and decremental ranges, that can be either inclusive or exclusive, far outweighs the slight stumbling block of "what does ^1 .. 10 mean?" Have a warning that it's meaningless and ignore it seems the simplest solution to that one. |
Beta Was this translation helpful? Give feedback.
-
I'm locking this as the OP deleted their post. That indicates no more desire to discuss things afaict. |
Beta Was this translation helpful? Give feedback.
Moving to runtime. This is not a lang issue.