In C# 3.0, I\'m liking this style:
// Write the numbers 1 thru 7
foreach (int index in Enumerable.Range( 1, 7 ))
{
Console.WriteLine(index);
}
I agree that in many (or even most cases) foreach
is much more readable than a standard for
-loop when simply iterating over a collection. However, your choice of using Enumerable.Range(index, count)
isn't a strong example of the value of foreach
over for.
For a simple range starting from 1, Enumerable.Range(index, count)
looks quite readable. However, if the range starts with a different index, it becomes less readable because you have to properly perform index + count - 1
to determine what the last element will be. For example…
// Write the numbers 2 thru 8
foreach (var index in Enumerable.Range( 2, 7 ))
{
Console.WriteLine(index);
}
In this case, I much prefer the second example.
// Write the numbers 2 thru 8
for (int index = 2; index <= 8; index++)
{
Console.WriteLine(index);
}