goto statement

In this chapter you will learn:

  1. How to use goto statement
  2. Use goto with a switch

Get to know goto statement

goto statement jumps to another labeled location. It has the form of

goto label;

When using with switch statement its form is

goto case caseConstant;
using System;/*from  ja v  a2 s  . co  m*/

class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
        {
            if (i == 1)
            {
                goto end;
            }
        }
    end: Console.WriteLine("The end");

    }
}

The output:

Use goto with a switch

The goto is C#'s unconditional jump statement. When encountered, program flow jumps to the location specified by the goto. The goto requires a label for operation. A label is a valid C# identifier followed by a colon.

using System; // j a  va 2  s .  c om
 
class SwitchGoto {   
  public static void Main() { 
 
    for(int i=1; i < 5; i++) { 
      switch(i) { 
        case 1: 
          Console.WriteLine("In case 1"); 
          goto case 3; 
        case 2: 
          Console.WriteLine("In case 2"); 
          goto case 1; 
        case 3: 
          Console.WriteLine("In case 3"); 
          goto default; 
        default: 
          Console.WriteLine("In default"); 
          break; 
      } 
      Console.WriteLine(); 
    } 
  } 
}

The code above generates the following result.

In case 1 In case 3 In default In case 2 In case 1 In case 3 In default In case 3 In default In default

Next chapter...

What you will learn in the next chapter:

  1. How to write Standard Xml documentation tags
  2. Standard Xml documentation tags
  3. Documentation Comments for a method with parameters
  4. see also and reference
Home » C# Tutorial » Statements
Comments
if Statement
while loop
do...while loop
for loop
foreach
switch
break
continue statement
goto statement
Xml Documentation