goto Statement in C#

 

goto statement in C# is use to immediately transfers flow of control to the statement following a label.

If we are using the goto statement in any loop statement, for example in While loop or do-while loop or for loop, then it will terminates the loop and shift to the mentioned loop as shown below.

 

using System; 

using System.Collections.Generic;

using System.Linq; 

using System.Text; 

 

namespace GoToExample 

{ 

 

   class Program 

   {

         static void Main(string[] args) 

        { 

         

             int i; 

             i = 0;

 

            while (i < 10) 

            {

 

                if (i == 2) 

                    goto label1;

 

                i = i + 1; 

            }

 

        label1: 

            Console.WriteLine("Number is 2"); 

      }      

  }

}

 

As shown above, we are using the while loop and inside the while loop we are checking the i variable value, whenever the i variable value becomes 2 we are shifting the execution flow to label  label1 by using the goto statement in C#.


                                                                                                                                  GoToExample.zip (19.13 kb)