Skip to content
Tutorials Center
My learning

Topics

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.

C#
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

C# Skipping and stopping

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.

C# Nested loops

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

C#
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 switch inside a loop: break leaves only the switch, not the loop. To skip to the next iteration from a switch section use continue; to leave the loop use return, goto or a flag.
  • Inside try/finally: break and continue run pending finally blocks before jumping. Both are fine inside try and catch, but not inside finally.
  • continue in while: be sure the variable that the condition depends on is updated before the continue, or the loop never ends.
  • Readability: an early continue often removes a level of nesting (a guard clause for loops). Overusing break in 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 labelled goto (see goto). Java-style labelled break does not exist in C#.
  • yield break is a different statement: it ends an iterator method (see yield).