-1

In C#, suppose there are two nested loops (each loop can be either while or for loop). In the middle of the inner loop, I would like to break out of both loops when a condition is true,

loop1
{
    ...
    loop2
    {
        ...
        (I want to break out of both loops, when some condition is true)
        ...
    }
    ...
}

Is there a more elegant way than

loop1
{
    ...
    loop2
    {
        ...
        if (condition)
            break
        ...
    }
    if (condition)
        break
    ...
}

Thanks.

Tim
  • 1
  • 141
  • 372
  • 590
  • 1
    I'd create a function with these loops and use `return`, because if you had more code after your loop block, calling return would make them not to be executed, that's why I'd put them in a separate function. – Alisson Reinaldo Silva Apr 06 '17 at 16:35
  • this is one of the few times it's generally accepted as allowable to use a `goto` statement. Though there are other ways to solve the problem – Jonesopolis Apr 06 '17 at 16:35
  • @Jonesopolis I don't know if this is an exact duplicate. A `goto` would be fine but it could also be wrapped in a function and returned. Which is what I would do. And isn't an exact duplicate of the other question. – Austin Winstanley Apr 06 '17 at 16:38

1 Answers1

1

Put it in a method and return;

public void TheLoops() 
{
    while(true) {
        while(true) {
            if (condition) {
                return;
                // or change void to a type and
                // return conditionResult;
            }
        }
    }
}
Austin Winstanley
  • 1,339
  • 9
  • 19