41

I am converting some Java code to C# and have found a few labelled "break" statements (e.g.)

label1:
    while (somethingA) {
       ...
        while (somethingB) {
            if (condition) {
                break label1;
            }
        }
     }

Is there an equivalent in C# (current reading suggests not) and if not is there any conversion other than (say) having bool flags to indicate whether to break at each loop end (e.g.)

bool label1 = false;
while (somethingA)
{
   ...
    while (somethingB)
    {
        if (condition)
        {
            label1 = true;
            break;
        }
    }
    if (label1)
    {
        break;
    }
}
// breaks to here

I'd be interested as to why C# doesn't have this as it doesn't seem to be very evil.

peter.murray.rust
  • 37,407
  • 44
  • 153
  • 217

1 Answers1

50

You can just use goto to jump directly to a label.

while (somethingA)
{
    // ...
    while (somethingB)
    {
        if (condition)
        {
            goto label1;
        }
    }
}
label1:
   // ...

In C-like languages, goto often ends up cleaner for breaking nested loops, as opposed to keeping track of boolean variables and repeatedly checking them at the end of each loop.

chwarr
  • 6,777
  • 1
  • 30
  • 57
Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • 9
    You're welcome. I didn't realize Java had labeled statements, so that makes us even :P – Mark Rushakoff Oct 10 '09 at 15:03
  • 9
    A `return` is cleaner, if you can structure it that way. – Robert Harvey May 23 '13 at 20:47
  • 2
    @MarkRushakoff, you should edit your answer... he wasn't really asking about boolean variables for loop control, so you shouldn't confuse the issue by bringing them up. In addition, goto is not really as good as labeled breaks because goto does not enforce branching only to the exit of a block... you can goto anywhere – JoelFan Nov 27 '14 at 18:19
  • 6
    @JoelFan I would like to point out to future readers that `goto` is limited to the scope of the containing method, and is unable to jump over variable declarations. You cannot jump outside of the containing method. This rings true even today in `C#`. – Hazel へいぜる Jan 22 '19 at 15:39