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 ususually use for, cause it's simple. I use while when counter is needed after or before loop or if using for is impossible.
How about the best of both worlds:
for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++)
Edit: Now that I think about it, I suppose comparing against int.MaxValue wasn't part of the criteria, but something to emulate an endless for loop, in that case you could just use:
for (int iLoop = 0; !Criterea; iLoop++)
There's no reason not to use a for
loop in this case. Even if you have other criteria, it's perfectly valid to write:
for (int iLoop = 0; iLoop < int.MaxValue && Criteria; iLoop++) { ... }
Personally I would go with the for loop.
It is better to read, more commonly used and very optimized.
for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++)
{
// Do Work
}
Edit: int.MaxValue && !Criteria <- a definietely better approach than my initial one ;)
You can always add the exit criteria to for loop:
for (int iLoop = 0; iLoop < int.MaxValue && Criteria; iLoop++)
{
//Maybe do work here
}
I would really go for whatever looks most readable in your particular case.
for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++) {
//Do work here...
}