C# Reference ยท Keywords and Statements
The break and continue statements
Reference for C# break and continue: leaving loops and switch sections, skipping iterations, nested loops, labels via goto and common mistakes.
break ends the innermost enclosing loop (for, foreach, while, do) or switch statement immediately; execution continues with the statement after it. continue abandons the current iteration of the innermost loop and moves on to the next one: in a for loop it runs the iterator and then tests the condition, in while and do it goes straight to the condition.
Neither statement can cross a method or lambda boundary, and neither takes a label. To leave several nested loops at once you need a flag, a helper method with return, or goto.
foreach (int n in numbers) { if (n < 0) continue; // skip negatives if (n > 100) break; // stop at the first too-large value total += n; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
break; continue;
Both are complete statements with no operands.
Errors: using break or continue outside a loop (and break also outside a switch) gives CS0139 ("No enclosing loop out of which to break or continue"). Jumping out of a finally block is not allowed (CS0157), and a break cannot leave an anonymous function.
Usage notes
- Inside
switchinside a loop:breakleaves only theswitch, not the loop. To skip to the next iteration from a switch section usecontinue; to leave the loop usereturn,gotoor a flag. - Inside
try/finally:breakandcontinuerun pendingfinallyblocks before jumping. Both are fine insidetryandcatch, but not insidefinally. continueinwhile: be sure the variable that the condition depends on is updated before thecontinue, or the loop never ends.- Readability: an early
continueoften removes a level of nesting (a guard clause for loops). Overusingbreakin several places can make the exit conditions hard to see; consider putting them into the loop condition. - Leaving nested loops: the cleanest options are a local function or method with
return, a boolean flag checked by the outer loop, or a labelledgoto(see goto). Java-style labelledbreakdoes not exist in C#. yield breakis a different statement: it ends an iterator method (see yield).