How to break out of multiple loops at once in C#?

Nick Heiner picture Nick Heiner · Feb 26, 2010 · Viewed 46.7k times · Source

What if I have nested loops, and I want to break out of all of them at once?

while (true) {
    // ...
    while (shouldCont) {
        // ...
        while (shouldGo) {
            // ...
            if (timeToStop) {
                break; // Break out of everything?
            }
        }
    }
}

In PHP, break takes an argument for the number of loops to break out of. Can something like this be done in C#?

What about something hideous, like goto?

// In the innermost loop
goto BREAK
// ...
BREAK: break; break; break;

Answer

Michael Anderson picture Michael Anderson · Feb 26, 2010

Extract your nested loops into a function and then you can use return to get out of the loop from anywhere, rather than break.