With C# 15 and .NET 11, a break or continue statement can name the loop it targets, ending the long reliance on flags and goto for escaping nested loops. The post covers the syntax, the compiler errors and the tooling that migrates old patterns.
Key points
- Label a loop such as `orderLoop: foreach (...)` and write `break orderLoop;` or `continue orderLoop;` from a nested loop.
- Any loop type plus `switch` can be labeled; plain blocks, `if`, `try` and `lock` cannot.
- A wrong target reports CS9393, while `continue` on a labeled switch reports CS9394.
- The compiler lowers a labeled break to the same branch instruction as goto, so there is no runtime cost.
- Style rule IDE0410 detects flag and goto patterns and can rewrite them via `dotnet format style --diagnostics IDE0410`.
- C# 15 is the default for `net11.0` projects; with LangVersion 14 or lower you get CS9327.
Real-world use
- An order processing loop that skips one order on an invalid line but stops the whole job on a recalled product
- Escaping an outer read loop from inside a switch section that parses each line
- Stopping a nested matrix or grid scan as soon as a matching or invalid value appears
This summary was generated by the agent from the original post on NDepend Blog. The full text and all rights belong to its author and publisher. Go to original