Thoughts on foreach with Enumerable.Range vs traditional for loop

前端 未结 18 1228
花落未央
花落未央 2021-01-30 06:13

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);
}
18条回答
  •  灰色年华
    2021-01-30 06:44

    I think the foreach + Enumerable.Range is less error prone (you have less control and less ways to do it wrong, like decreasing the index inside the body so the loop would never end, etc.)

    The readability problem is about the Range function semantics, that can change from one language to another (e.g if given just one parameter will it begin from 0 or 1, or is the end included or excluded or is the second parameter a count instead a end value).

    About the performance, I think the compiler should be smart enough to optimize both loops so they execute at a similar speed, even with large ranges (I suppose that Range does not create a collection, but of course an iterator).

提交回复
热议问题