Breaking out of a foreach loop from within a switch block

c# break out of for loop
c# break nested loop
skip iteration of loop c#
c# break out of if
for loop continue and break
c# loop continue vs break
break and continue statement in c#
switch case c#

How do you break out of a foreach loop while within a switch block?

Normally, you use break but if you use a break within a switch block it will just get you out of a switch block and the foreach loop will continue execution:

foreach (var v in myCollection)
{
    switch (v.id)
    {
        case 1:
            if (true)
            {
                break;
            }
            break;
        case 2;
            break
    }
}

What I'm currently doing when I need to break out of the foreach while within the switch block is setting a bool value placed outside of the loop to true and checking the value of this bool every time the foreach is entered and before entering the switch block. Something like this:

bool exitLoop;
foreach (var v in myCollection)
{
    if (exitLoop) break;
    switch (v.id)
    {
        case 1:
            if (true)
            {
                exitLoop = true;
                break;
            }
            break;
        case 2;
            break
    }
}

This works but I keep thinking there must be a better way of doing this I am unaware of...

EDIT: Wonder why this was not implemented in .NET the really neat way it works in PHP as mentioned by @jon_darkstar?

$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "At 5<br />\n";
        break 1;  /* Exit only the switch. */
    case 10:
        echo "At 10; quitting<br />\n";
        break 2;  /* Exit the switch and the while. */
    default:
        break;
    }
}

Your solution is pretty much the most common option in this case. That being said, I'd put your exit check at the end:

bool exitLoop;
foreach (var v in myCollection)
{
    switch (v.id)
    {
        case 1:
            if (true)
            {
                exitLoop = true;
            }
            break;
        case 2;
            break
    }

    // This saves an iteration of the foreach...
    if (exitLoop) break;
}

The other main option is to refactor your code, and pull the switch statement and foreach loop out into a separate method. You could then just return from inside the switch statement.

Breaking out of a foreach loop from within a switch block, How do you break out of a foreach loop while within a switch block? bool exitLoop; foreach (var v in myCollection) { if (exitLoop) break; switch (v.id) { case 1: if  Stack Overflow Public foreach loop within while loop - break out of foreach and continue on the while loop right away? Breaking out of a foreach loop from


The boolean is one way. Another is using labels and goto. I know folks consider goto to be a cardinal sin, but used judiciously (VERY judiciously), it can be useful. In this case, place a label just past the end of the foreach loop. When you want to exit the loop, simply goto that label. For example:

foreach(var v in myCollection) {
    switch(v.Id) {
        case 1:
            if(true) {
                goto end_foreach;
            }
            break;
        case 2:
            break;
    }
}
end_foreach:
// ... code after the loop

EDIT: some people have mentioned taking the loop out into a separate method so that you can use return. I see the benefit of this as it doesn't require goto and it also simplifies the original function that contained the loop. However, if the loop is simple and is the primary purpose of the function that contains it, or if the loop makes use of out or ref variables, then it's probably best to just leave it in place and use the goto. In fact, because the goto and the label stand out, it probably makes the code clearer rather than clunkier. Putting it in a separate function could make simple code harder to read.

break - Manual, break ends execution of the current for, foreach, while, do-while or switch structure. 7.0.0, break outside of a loop or switch control structure is now detected at It's not necessary to break out of any case of a switch statement in PHP, but if  A 'break' in a case block will only apply to the switch statement, to break the loop you need to issue break outside the switch(), you could do something like the following: foreach (Control check in this.Controls)


You could extract your foreach cycle to the separate method and use return statement. Or you could do like this:

        foreach (object collectionElement in myCollection)
        {
            if (ProcessElementAndDetermineIfStop(collectionElement))
            {
                break;
            }
        }

        private bool ProcessElementAndDetermineIfStop(object collectionElement)
        {
            switch (v.id)
            {
                case 1:
                    return true; // break cycle.
                case 2;
                    return false; // do not break cycle.
            }
        }

continue - Manual, Note: In PHP the switch statement is considered a looping structure for the purposes of continue. foreach ($arr as $key => $value) { break 1 - break 2 and observed the different results. This made me come up with the Switch is documented as a block of ifelseif statements, so you might expect the following output: The Break statement is used to exit a looping statement such as a Foreach, For, While, or Do loop. When present, the Break statement causes Windows PowerShell to exit the loop. The Break statement can also be used in a Switch statement. Note For more information about looping in Windows PowerShell script, take a look at these Hey, Scripting Guy!


Honestly? This is perhaps the only situation where it is completely valid and proper to use goto:

foreach (var v in myCollection) {
    switch (v.id) {
        case 1:
            if (true)
                // document why we're using goto
                goto finished;
            break;
        case 2;
            break
    }
}
finished: // document why I'm here

C# break Statement, Use break to end a block in a switch statement. Here we see the break keyword in the for-loop and foreach-loop constructs. Program { static void Main​() { break; } } Output Error CS0139 No enclosing loop out of which to break or continue. Switch and break; inside a foreach loop. PHP. jjshell. August 30, 2014, 4:00am #1. Hello, I’m using a swtich inside a foreach loop. should break you out of the switch and the loop


It's not really different from your exitLoop flag, but it might be more readable if you extract a method...

foreach (var v in myCollection)
{
    if(!DoStuffAndContinue(v))
        break;
}


bool DoStuffAndContinue(MyType v)
{
    switch (v.id)
    {
        case 1:
            if (ShouldBreakOutOfLoop(v))
            {
                return false;
            }
            break;
        case 2;
            break;
    }
    return true;
}

about_Break, When a break statement appears in a loop, such as a foreach , for , do , or while loop, break moves execution out of the labeled loop. In In a switch construct, break causes PowerShell to exit the switch code block. When a Break statement appears in a loop, such as a Foreach, For, Switch, or While loop, the Break statement causes Windows PowerShell to immediately exit the loop. In a Switch construct that does not loop, Break causes Windows PowerShell to exit the Switch code block. from help about_continue:


JavaScript Break and Continue, The continue statement "jumps over" one iteration in the loop. The break statement can also be used to jump out of a loop. the continue statements are the only JavaScript statements that can "jump out of" a code block. The break statement, without a label reference, can only be used to jump out of a loop or a switch. If you think about break being a function like break(), then it's parameter would be the number of loops to break out of. As we are in the third loop in the code here, we can break out of all three. As we are in the third loop in the code here, we can break out of all three.


C# foreach statement, statement causes the conditional test and increment portions of the loop to execute. Using a labeled break in a loop. A break statement can include a label. If you use the break keyword with a label, PowerShell exits the labeled loop instead of exiting the current loop. The label is a colon followed by a name that you assign. The label must be the first token in a statement, and it must be followed by the looping keyword, such as while. break moves execution out of


PHP - Loop Types, Break stops loop and is used within switch statements. And: Control is immediately transferred to the statement following the enclosing block. C# program that  Break will terminate\exit from a loop. Break will exit from the current loop iteration and will jump to the outer loop if it exists. Use Label to control the flow of code once Break keyword is encountered in code to override its default behavior. Now let’s move on to the next keyword i.e. Continue.