Using C# (or VB.NET) which loop (for loop or do/while loop) should be used when a counter is required?
Does it make a difference if the loop should only iterate a se
I'd tend to use for
if I'm actually using the counter in the loop, say as an index into an array, and as part of the criteria, i.e. "stop at the end of the array" rather than "just don't overflow".
If I'm looping over something with unknown length, such as lines in a file, or just maintaining the counter to use the total after the loop, then I'll use do
or while
.
However, it really comes down to what's more readable for a particular situation. I expect that you'd struggle to tell from the compiled IL which version was used.