C# adaptation of approach often used in C - set value of outer loop's variable outside of loop conditions (i.e. for loop using int variable INT_MAX -1
is often good choice):
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
if (exit_condition)
{
// cause the outer loop to break:
// use i = INT_MAX - 1; otherwise i++ == INT_MIN < 100 and loop will continue
i = int.MaxValue - 1;
Console.WriteLine("Hi");
// break the inner loop
break;
}
}
// if you have code in outer loop it will execute after break from inner loop
}
As note in code says break
will not magically jump to next iteration of the outer loop - so if you have code outside of inner loop this approach requires more checks. Consider other solutions in such case.
This approach works with for
and while
loops but does not work for foreach
. In case of foreach
you won't have code access to the hidden enumerator so you can't change it (and even if you could IEnumerator
doesn't have some "MoveToEnd" method).
Acknowledgments to inlined comments' authors:
i = INT_MAX - 1
suggestion by Meta
for
/foreach
comment by ygoe.
Proper IntMax
by jmbpiano
remark about code after inner loop by blizpasta