C# goto statement

In this chapter you will learn:

  1. What is goto statement
  2. How to create goto statement
  3. Example for goto statement
  4. Use goto with a switch

Description

The goto statement transfers execution to another label within the statement block.

Syntax

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;

A label statement is just a placeholder in a code block, denoted with a colon suffix.

Example

Example for goto statement


using System;//from w  w  w . j  a va 2  s. c  om

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:

Example 2

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; //w w w.j  a va  2s  . com
 
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.

Next chapter...

What you will learn in the next chapter:

  1. What is XML Documentation
  2. Syntax to use XML document
  3. XML Documentation Standard Tag
  4. Example
  5. see also and reference
Home »
  C# Tutorial »
    C# Language »
      C# Statements
C# Comments
C# if statement
C# while loop
C# do while loop
C# for loops
C# foreach statement
C# switch statement
C# break statement
C# continue statement
C# goto statement
C# XML Documentation