Goto statement in C#


Goto  statement  In  C#

The goto is C#  unconditional jump statement. When encountered, program flow jumps to the location specified by the goto.

The goto requires a label of operation. A label is a valid C# identifier followed by colon.

There are different-different ways for using Goto statement such as:

  1. We can write code for loop with the help of goto statement

            int x = 1;

        Loop:

            x++;

            if (x < 100)

            {

                goto loop;

            }

  1. The goto can also be used to jump to a case or default statement in a switch

         Here is the example

string Fruit = "Apple";

            switch (Fruit)

            {

                case "Banana":

                    MessageBox.Show(Fruit + " is the delecious fruit");

                    break;

                case "Chair":

                    MessageBox.Show(Fruit + " is the delecious fruit");

                    break;

                case "Apple":

                    goto case "Banana";

                case "Table":

                    goto case "Chair";

                default:

                    MessageBox.Show("Select valid option");

                    break;

            }

          

In this case, case and default statements of a Switch are labels thus they can be targets of a goto. However, the goto statement must be executed from within the switch. that is we cannot use the goto to jump into switch statement .

  1. With while, we can understand easily with this example

int a = 0;

            while (a < 10)

            {

                if (a == 5)

                    goto cleanup;

            }

        cleanup:         
            
MessageBox.Show(a);

Up Next
    Ebook Download
    View all
    Learn
    View all