Breaking out of a nested loop
Well, goto
, but that is ugly, and not always possible. You can also place the loops into a method (or an anon-method) and use return
to exit back to the main code.
// goto
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
goto Foo; // yeuck!
}
}
Foo:
Console.WriteLine("Hi");
vs:
// anon-method
Action work = delegate
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits anon-method
}
}
};
work(); // execute anon-method
Console.WriteLine("Hi");
Note that in C# 7 we should get "local functions", which (syntax tbd etc) means it should work something like:
// local function (declared **inside** another method)
void Work()
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits local function
}
}
};
Work(); // execute local function
Console.WriteLine("Hi");
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