Nick Heiner
Nick Heiner

Reputation: 122412

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

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;

Upvotes: 81

Views: 65591

Answers (5)

schrdori
schrdori

Reputation: 51

You can just use goto to get out of the loops:

    [...]    
       while (true) {
            // ...
            while (shouldCont) {
                // ...
                while (shouldGo) {
                    // ...
                    if (timeToStop) {
                        goto GETOUT;
                    }
                }
            }
        } 
        GETOUT: 
        //move on to the next step
    [...]
    

Upvotes: 3

tolu619
tolu619

Reputation: 31

If you want to break out of an entire method, then use the code below. If you only want to break out of a series of loops within a method without breaking out of the method, then one of the answers that have already been posted will do the job.

if (TimeToStop)
{
   return;
}

Upvotes: 3

Fadrian Sudaman
Fadrian Sudaman

Reputation: 6465

Introduce another control flag and put it in all your nested while condition like below. Also replaces the while(true) condition you have with that

bool keepLooping = true;
while (keepLooping) {
    // ...
    while (shouldCont && keepLooping) {
        // ...
        while (shouldGo && keepLooping) {
            // ...
            if (timeToStop) { 
                keepLooping  = false;
                break; // break out of everything?
            }
        }  
    }
}

Upvotes: 77

Michael Anderson
Michael Anderson

Reputation: 73470

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

Upvotes: 95

Andrew
Andrew

Reputation: 12009

Goto is only hideous when abused. To drop out of the innermost loop of some nesting it's acceptable. BUT... one has to ask why there is so much nesting there in the first place.

Short answer: No.

Upvotes: 29

Related Questions