Post

C# 15 lets you break out of nested loops by name

See labeled break and continue in action with seat search and talk scheduling, and learn when a separate method is the better option.

C# 15 lets you break out of nested loops by name

C# 15 came with .NET 11 on November 10. Most of the attention went to union types, but the same release has a much smaller feature that touches more everyday code: labeled break and continue.

Until now, break and continue worked only on the innermost loop. To leave two loops at once, you needed a flag, a goto or a separate method. In C# 15, you put a label on a loop and name that label in the jump statement.

Finding seats for a group

People often come to a meetup in groups and want to sit together. Let’s say the room is an array of rows, each row is an array of seats, and true means the seat is taken. We need the first block of groupSize free seats next to each other in one row.

That takes three loops: rows, the first seat of a block, and the seats inside the block. This is how it usually looked with flags:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
(int Row, int First)? block = null;

for (int row = 0; row < taken.Length; row++)
{
    for (int first = 0; first + groupSize <= taken[row].Length; first++)
    {
        bool allFree = true;
        for (int seat = first; seat < first + groupSize; seat++)
        {
            if (taken[row][seat])
            {
                allFree = false;
                break;
            }
        }

        if (allFree)
        {
            block = (row, first);
            break;
        }
    }

    if (block is not null)
    {
        break;
    }
}

Two jumps need two checks. allFree tells the middle loop to skip a start position, and the null check on block tells the outer loop to stop.

The goto version is shorter, but its labels sit far away from the loops they belong to. nextStart: also needs an empty statement (;), since C# requires a statement after every label:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
for (int row = 0; row < taken.Length; row++)
{
    for (int first = 0; first + groupSize <= taken[row].Length; first++)
    {
        for (int seat = first; seat < first + groupSize; seat++)
        {
            if (taken[row][seat])
            {
                goto nextStart;
            }
        }

        block = (row, first);
        goto done;

    nextStart: ;
    }
}

done:
return block;

The same search with labels

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
rows: for (int row = 0; row < taken.Length; row++)
{
    starts: for (int first = 0; first + groupSize <= taken[row].Length; first++)
    {
        for (int seat = first; seat < first + groupSize; seat++)
        {
            if (taken[row][seat])
            {
                continue starts;
            }
        }

        block = (row, first);
        break rows;
    }
}

continue starts moves to the next start position as soon as one seat in the block is taken. break rows leaves both loops when we have a block. A break or continue without a label works as before, on the innermost loop.

The label sits directly on the loop, so it names the loop itself. With goto, a label marks a position in the code, and you have to put it in the right place yourself. A labeled break can also target a switch statement, while continue works only with loops.

Does a labeled break cost anything at runtime?

No. In Release, the labeled version of the seat search compiles to the same IL as the goto version, byte for byte (79 bytes). So the label costs nothing over goto. The flag version has 102 bytes because of the extra local and the checks. The JIT may remove some of that work, so I wouldn’t treat the difference as a speed result.

Continue the outer loop after a match

The second pattern I find useful is “find a match, then go to the next item”. Here we plan a meetup evening. Every time slot can hold one talk, and the speaker must be available at that time:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Dictionary<TimeOnly, Talk> schedule = [];
List<Talk> unscheduled = [];

talks: foreach (Talk talk in talks)
{
    foreach (TimeOnly slot in slots)
    {
        if (schedule.ContainsKey(slot) || !availability[talk.Speaker].Contains(slot))
        {
            continue;
        }

        schedule[slot] = talk;
        continue talks;
    }

    unscheduled.Add(talk);
}

continue talks skips the rest of the outer loop body, so unscheduled.Add(talk) runs only when no slot was found. Before C# 15, this usually meant an assigned flag that you set in the inner loop and checked after it.

Can I break out of a loop from inside a switch?

Yes. Inside a switch statement, a plain break ends the switch section and the loop keeps going. To stop the loop from a case, you needed a flag or goto. Now break can name the loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
queue: while (events.TryDequeue(out RegistrationEvent? e))
{
    switch (e)
    {
        case SignedUp s:
            attendees.Add(s.Email);
            break;
        case Cancelled c:
            attendees.Remove(c.Email);
            break;
        case RegistrationsClosed:
            break queue;
    }
}

If a late sign-up arrives after RegistrationsClosed, the loop stops before it and the event stays in the queue. A plain continue inside a switch has always continued the enclosing loop, so in this case the label matters only for break.

Compiler errors for a wrong label

I tried the mistakes that seemed most likely and wrote down the diagnostics:

CodeResult
break rows; where rows labels an earlier loop, not one around the breakCS9393: No enclosing loop or switch statement with the label ‘rows’ out of which to break
break block; where block labels a { } blockCS9393
break nowhere; with no such labelCS9393
break a; in a: b: while (...)CS9393, because only b labels the loop
continue choice; where choice labels a switchCS9394: No enclosing loop with the label ‘choice’ out of which to continue
break outer; inside a lambda in the loopCS1632: Control cannot leave the body of an anonymous method or lambda expression
break outer; inside a finally blockCS0157: Control cannot leave the body of a finally clause
two loops labeled outer next to each other in one methodCS0140: The label ‘outer’ is a duplicate

The last one is easy to hit. A label is visible in the whole block where you declare it, so you can’t use outer for two loops that sit one after another in the same method body. I prefer names that describe the loop, like rows or talks. They read better than outer and clash less often.

What IDE0410 catches

IDE0410 is the new style rule “Use labeled jump statement”. By default, dotnet build doesn’t show it. You need two settings: a severity in .editorconfig and EnforceCodeStyleInBuild in the project file:

1
2
[*.cs]
dotnet_diagnostic.IDE0410.severity = warning
1
2
3
<PropertyGroup>
  <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>

The .editorconfig entry alone is not enough. With both in place, the rule flagged both goto statements in the seat search. For flags, it looks for a bool that starts as false, is set to true in the inner loop and is checked in the outer one. A version of the seat search with blocked and found flags written that way got a warning on both inner break statements. The first version in this post got none, because allFree starts as true and the outer loop checks block for null. A clean build doesn’t mean there are no flags left.

The code fix (dotnet format style --diagnostics IDE0410) gives working code that finds the same seats. It keeps the old goto names, which gives you break done; and continue nextStart;, and for flags it makes up names like loop_row and loop_first. Rename the labels after the fix.

I would not make IDE0410 a build warning in CI. The rule can’t tell when a method would be the better change, and a warning pushes people to the quick fix.

When an extracted method is still better

Labeled jumps don’t replace the old advice to move nested loops into a method. For the seat search, a method is still my choice:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static (int Row, int First)? FindSeatsTogether(bool[][] taken, int groupSize)
{
    for (int row = 0; row < taken.Length; row++)
    {
        for (int first = 0; first + groupSize <= taken[row].Length; first++)
        {
            if (!taken[row].AsSpan(first, groupSize).Contains(true))
            {
                return (row, first);
            }
        }
    }

    return null;
}

return does the job of break rows. The method has a name that says what it does, and I can test it alone. The span check also removes the third loop, so there is nothing left for continue starts to do.

I would reach for a label in these cases:

  • the loops use many locals from the rest of the method, and a separate method would need several ref or out parameters
  • the code after the inner loop is the “not found” branch, like unscheduled.Add(talk) in the schedule
  • you need to stop a loop from inside a switch

If you can’t find a good name for the label, that’s a hint to move the loop into a method.

Try it

You need the .NET 11 SDK and a project that targets net11.0. C# 15 is the default language version there, so there is nothing to turn on. I built every sample in this post with SDK 11.0.100.

Sources:

Cover image generated with gpt-image-2.5-sunburst from my photo.

This post is licensed under CC BY 4.0 by the author.