C# 15 Labeled break and continue: Exit Nested Loops Cleanly
In C#, the break keyword only ever leaves the innermost loop. When you're two loops deep and want out of both, C# 15 finally lets you say exactly which loop you mean.
In lesson 012 you learned two handy loop keywords: break leaves a loop early, and continue skips to the next round of a loop. They work beautifully, as long as there's only one loop.
Put one loop inside another, which is common when you work with grids, tables, or orders that contain items, and a problem appears: break and continue only affect the innermost loop. To leave the outer loop, programmers used extra true/false variables or the old goto statement. Both work, and both make code harder to read.
In this lesson, you'll learn C# 15's labeled break and continue: how to give a loop a name, how to jump out of or continue that named loop from deep inside, and the simple rules that keep it safe.
What Is It?
The Simple Explanation
You can put a label (a name followed by a colon) right in front of a loop. Then, from anywhere inside it, even inside a nested loop, break label; leaves that loop and continue label; jumps to its next round.
outer: for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++)
{
if (col == 2) continue outer; // jump straight to the next row
if (row == 2) break outer; // leave BOTH loops
Console.WriteLine($"{row},{col}");
}
}
// Prints: 0,0 0,1 1,0 1,1The Technical Definition
Starting with C# 15, break and continue statements can optionally name a label on an enclosing statement. A labeled break exits the labeled loop or switch statement and continues with the statement after it. A labeled continue starts the next iteration of the labeled loop; it can't target a switch. The label must be placed directly on the loop or switch it identifies. Without a label, both statements behave exactly as before.
Before C# 15
- A bool found flag set inside, then checked in every outer loop
- Or goto to a label placed after the loops
- Or moving the loops into a method just to use return
With C# 15
- break outer; leaves the loop named outer directly
- continue outer; moves to that loop's next round
- No flags and no goto: the intent is in one line
Why Does It Exist?
The Problem — Escaping Nested Loops Was Clumsy
Here is how people searched a grid before C# 15. Notice how much code exists only to get out of the loops:
bool found = false;
for (int row = 0; row < grid.Length; row++)
{
for (int col = 0; col < grid[row].Length; col++)
{
if (grid[row][col] == target)
{
found = true;
break; // only leaves the inner loop...
}
}
if (found) break; // ...so the outer loop has to check again
}The Solution — Name the Loop You Mean
C# 15 lets you name the outer loop and break out of it directly. Many other languages, including Java, JavaScript and Rust, have had this for years. It makes the intended control flow obvious, and the .NET analyzers even include a style rule, IDE0410, that spots flag and goto patterns that a labeled jump could replace.
Big Picture
How It Works
- outer: for (...) gives the outer loop the name outer. Only the statement directly after the label gets that name.
- Nothing changes until a labeled break or continue runs.
- The inner loop ends immediately, and so does the outer loop.
- The program carries on with the first statement after outer. With continue outer; instead, it would go to the outer loop's next round.
Simple Example
Find the first pair of numbers in a list that add up to a target:
int[] numbers = [3, 8, 12, 5, 7];
int target = 15;
(int First, int Second)? found = null;
search: for (int i = 0; i < numbers.Length; i++)
{
for (int j = i + 1; j < numbers.Length; j++)
{
if (numbers[i] + numbers[j] == target)
{
found = (numbers[i], numbers[j]);
break search; // stop searching completely
}
}
}
Console.WriteLine(found is { } pair ? $"{pair.First} + {pair.Second}" : "No pair");
// 3 + 12Code → Meaning → Result: The outer loop is labeled search. As soon as 3 + 12 = 15 is found, break search; leaves both loops at once, so the pair 8 + 7, which also adds up to 15, is never checked. No flag variable is needed.
Real-World Example
A shop checks each order before shipping. If any item in an order is out of stock, the whole order should be skipped and the checker should move straight to the next order:
var stock = new Dictionary<string, int> { ["pen"] = 10, ["ink"] = 0, ["pad"] = 4 };
List<List<string>> orders =
[
["pen", "pad"],
["pen", "ink"], // ink is out of stock
["pad"],
];
orderLoop: foreach (List<string> order in orders)
{
foreach (string item in order)
{
if (stock[item] == 0)
{
Console.WriteLine($"Skipping order ({item} is out of stock)");
continue orderLoop; // go straight to the next ORDER, not the next item
}
}
Console.WriteLine($"Shipping: {string.Join(", ", order)}");
}
// Shipping: pen, pad
// Skipping order (ink is out of stock)
// Shipping: padWithout the label, continue would only skip to the next item, and the half-checked order would still reach the "Shipping" line. continue orderLoop; says exactly what you mean: this order is done, move on to the next one.
Analogy
You're inspecting a building floor by floor, and room by room on each floor. A plain continue means "skip to the next room". A plain break means "stop inspecting this floor".
Labeled jumps let you name the floor loop. continue floors; means "this whole floor fails; go to the next floor". break floors; means "stop the whole inspection and leave the building".
Under the Hood
- Structured, unlike goto. A labeled break or continue can only target a loop (or, for break, a switch statement) that encloses it. You can't jump sideways or into another block, which is what made goto hard to follow.
- One label per statement. In a: b: while (...), only the statement directly after a label has that label, so the while loop is b, not a.
- continue needs a loop. continue can target for, foreach, while and do loops, but not a switch statement.
- Analyzer help. Style rule IDE0410 points out flag variables and goto statements that a labeled break or continue could replace, and shows the cleaner version.
Common Confusion
1. "This is just goto with a new name" — no, it's much more limited (and safer)
goto can jump to almost any label in a method. A labeled break or continue can only target a loop or switch that contains it, so its behaviour is always "leave this structure" or "next round of this structure".
2. "Now every break needs a label" — no, unlabeled break works as always
Labels are optional. A plain break; still leaves the innermost loop, so most loops never need a label.
3. "I can put the label anywhere above the loop" — no, it goes directly on the loop
Write outer: for (...), with the label immediately in front of the loop statement. A label on a blank line or on a different statement doesn't name the loop.
Common Mistakes
Mistake 1 — Using continue with a labeled switch
The mistake: Labeling a switch statement and writing continue mySwitch; inside it.
The fix: continue only works with loops. To leave a labeled switch, use break mySwitch;.
Mistake 2 — Labels on every loop "just in case"
The mistake: Adding labels to loops that never use them, which adds noise and makes readers hunt for the jump that uses them.
The fix: Only label a loop when an inner loop really needs to break or continue it. If the nesting gets deep, moving the loops into a small method and using return can be clearer still.
When Should I Use It?
- Searching nested data, such as grids, tables or lists of lists, where you want to stop as soon as you find something.
- Validating groups, such as orders and their items or files and their lines, where one bad item should skip the whole group.
- **Replacing old flag variables or goto statements** in existing code. IDE0410 will point them out.
- Not for single loops. Plain break and continue are already perfect there.
Mental Model
break name; = leave that loop completely. continue name; = next round of that loop.
No label = the innermost loop, exactly like before.
Remember: labels let a deeply nested line point at the exact loop it wants to leave or restart.
Key Takeaway
- C# 15 lets break and continue name an enclosing labeled statement: break outer;, continue outer;.
- Place the label directly on the loop or switch: outer: for (...).
- break label; exits a loop or switch; continue label; works only with loops.
- It replaces Boolean "found" flags and goto jumps for escaping nested loops, and IDE0410 helps you find them.
- Unlabeled break and continue are unchanged.
Check Your Understanding
Three quick questions on labels and loops.
1. Inside a nested loop, what does break outer; do, where the outer loop is written outer: for (...)?
Show answer
Correct: B
Why B is correct: A labeled break exits the named loop. Since the inner loop is inside it, both loops end and execution continues after the outer loop.
Why A is incorrect: That's what a plain, unlabeled break does.
Why C is incorrect: Nothing restarts. To move to the next round of the outer loop, you'd use continue outer;.
Why D is incorrect: Labeled jumps don't re-run anything. That kind of jump belongs to goto, which this feature avoids.
Reinforcement: break label = leave that loop completely.
2. In the shop example, why is continue orderLoop; used instead of continue;?
Show answer
Correct: B
Why B is correct: Plain continue affects the innermost loop, the items. continue orderLoop; jumps to the next round of the outer loop, so the rest of that order is skipped and "Shipping" isn't printed for it.
Why A is incorrect: continue; works in any loop, including foreach. It just targets the wrong loop here.
Why C is incorrect: Labels don't change speed. They only make it clear which loop you mean.
Why D is incorrect: continue never changes your data. It only controls which loop round runs next.
Reinforcement: Name the loop whose next round you actually want.
3. Which of these is NOT allowed?
Show answer
Correct: C
Why C is correct: A labeled continue must target a loop. A switch has no "next round", so continue can't name it.
Why A is incorrect: Breaking out of a labeled enclosing loop is the main use of the feature.
Why B is incorrect: A labeled break may target an enclosing switch statement as well as a loop.
Why D is incorrect: Unlabeled continue still works exactly as it always has.
Reinforcement: break: loops and switches. continue: loops only.
That completes the C# 15 language tour: unions, closed hierarchies, collection arguments, extension indexers and labeled jumps. The next lesson goes under the hood to a change you won't see in your code at all: runtime async.