Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Ruby "redo" in C#

Is there an equivalent method of performing the job of redo in C#? i.e. going back to the top of the loop and re-execute without checking conditions or increasing the loop counter. Thanks.

like image 682
Jurgen Camilleri Avatar asked Dec 04 '22 12:12

Jurgen Camilleri


2 Answers

for (int i = 0; i < 100; i++)
{
    do
    {
        DoYourStuff();
    } while (ShouldWeDoThatAgain());
}

Do...while is like a standard while loop, except instead of checking its conditional before each iteration, it checks after. That way, the code inside the loop will always execute at least once. Stick that inside a for or foreach loop, and that should get you the behavior your want. This is a bit simpler than Simon's answer, as it doesn't require an extra variable, doesn't use continue, and doesn't mess with the loop counter at all.

like image 108
ChimeraObscura Avatar answered Dec 15 '22 06:12

ChimeraObscura


Why not simply:

Although goto is not really everyone's favourite, it's quite readable in this case...

for(...)
{
redo:

   //...

   if (...)
      goto redo;




}
like image 29
Onur Avatar answered Dec 15 '22 08:12

Onur