Search code examples
c#winformsgoto

how GOTO works in c#


I have a for loop in c# winform and I want to start for loop again if i=7

The code looks like this :

 for (int i = 0; i < 10; i++)
        {
           if (i==7)
             {
               MessageBox.Show("you must start for loop again ");
              //here I want to go back to for loop again
             }
        }  

any ideas ?

also,I know this code makes no sense, I just wrote it for example — I have similar situation in my c# code.


Solution

  • In this case, just mutate i back to 0, like so:

    for (int i = 0; i < 10; i++)
    {
        if (i==7)
        {
            MessageBox.Show("you must start for loop again ");
            i = 0;
        }
    }
    

    If you really want to use goto, then here is an example for that:

    BackToTheStart:
      for (int i = 0; i < 10; i++)
      {
          if (i==7)
          {
              MessageBox.Show("you must start for loop again ");
              goto BackToTheStart;
          }
      }
    

    It's worth keeping in mind if you didn't already know, goto is generally considered bad practice and an unwelcome legacy baggage C# brought from C style languages of yesteryear. In most cases you do not need it, like in this example, it's easier not to use it. And, most importantly, no one will ever thank you for adding a goto.