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 set number of times or through a set range?
Scenario A - The for loop
for (int iLoop = 0; iLoop < int.MaxValue; iLoop++)
{
//Maybe do work here
//Test criteria
if (Criteria)
{
//Exit the loop
break;
}
//Maybe do work here
}
Advantages
- Counter is declared as part of loop
- Easy to implement counter range
Disadvantages
- Have to use an if to leave the loop
Scenario B - The do/while loop
int iLoop = 0;
do
{
//Increment the counter
iLoop++;
//Do work here
} while (Criteria);
or
int iLoop = 0;
while (Criteria)
{
//Increment the counter
iLoop++;
//Do work here
}
Advantages
- Leaving the loop is part of the loop structure
- Choice to evaluate before or after loop block
Disadvantages
- Have to manage the counter manually