-1

I want to control a while loop, if the result is "Continue" I want to do nothing, if it is "Retry" I want to skip the step, if it is "Finish" I want to break the loop.

The problem is the switch statement itself is using the "break" and "continue" keywords that I need to manage my loop.

while(some bool)
{
   var result = GetResult(...);
   switch(result)
   {
      case MyResult.Continue:
      //do nothing
      break;
      case MyResult.Retry:
      // continue the loop
      break;
      case MyResult.Finish:
      // break the loop
      break;
   }
}

Is this even possible or should I just do this with if else statements (after all, the scope of possible Results is not so big)?

Edit:

A.d. "Skip the step": Well, I wanted to over-generalize the process. Actually if the result is "Continue" I want to do execute some code, the merit of the question was if it is possible to use 'break' and 'continue' to control a loop from within the switch statement. So yes, the answer is already in here

adam.k
  • 324
  • 3
  • 14

1 Answers1

1

Your question is a little unclear around "skip the step" as you've not specified what this actually means but yes you can totally use a switch to manage the loop condition

bool continueLoop = true;
while(continueLoop)
{
   var result = GetResult(...);
   switch(result)
   {
      case MyResult.Continue:
      //do nothing
      break;
      case MyResult.Retry:
      // continue the loop
      break;
      case MyResult.Finish:
      // break the loop
      continueLoop = false;
      break;
   }
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • or even `for(bool continueLoop = true; continueLoop;) {...}` instead of `bool continueLoop = true; while(continueLoop) {...}` – Dmitry Bychenko Jun 14 '19 at 09:51
  • In general case `continueLoop = false; continue;` in case we have some code after `switch`: `while(...) {...switch(result) {} some_code_here}` – Dmitry Bychenko Jun 14 '19 at 09:57