Urgent.News

the world's headlines, one feed

Editions

Tech

C# 15 Finally Gets Labeled `break` and `continue`

Nested loops are easy to write. Getting out of them cleanly isn't always as easy. Consider a simple grid search: for ( int row = 0 ; row < grid . Height ; row ++) { for ( int column = 0 ; column < grid . Width ; column ++) { if ( grid [ row , column ]. IsGoal ) { // How do we exit both loops? } } } A normal break isn't enough: break ; It only exits the innermost loop. Until now, C# developers…

C# 15 introduces labeled `break` and `continue` statements to more cleanly exit nested loops. In deeply nested loops, using a normal `break` statement only exits the innermost loop, requiring additional mechanisms like Boolean flags or `goto` to exit outer loops. C# 15 allows labeling loops with a name, making it clear which loop should be exited.

For example, consider searching for a target value within a matrix using nested loops. Without labeled break, a Boolean flag (`found`) is used to indicate when to exit the loops. This flag is only used to propagate a `break` from the inner loop to the outer loop, becoming increasingly awkward as the nesting depth increases. With labeled `break`, a label (e.g., `outer`) is placed directly on the loop, and `break outer;` can be used to exit that labeled loop. This cleanly exits the labeled loop without the need for an extra flag or `goto`.

The same concept applies to `continue`. Before C# 15, using `continue` in deeply nested loops often required an additional flag to track when to skip the current iteration and move to the next one. With labeled `continue`, a label (e.g., `ordersLoop`) is placed on the loop, and `continue ordersLoop;` can be used to immediately move to the next iteration of the labeled loop.

This new syntax provides a more intuitive and readable way to handle nested loops, eliminating the need for temporary flags or `goto` statements.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — it may contain errors, so check the original before relying on it.

Read the original at dev.to →

More in Tech