C# Tutorial C# Advanced C# Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

C# - goto Statement



In C#, goto is a jump statement and sometimes also referred as unconditional jump statement. It can be used to jump from goto to a labeled statement within the same function. The target label must be within the same file and context.

Please note that the use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making hard to understand and modify the program.

Syntax

goto label;
...
...
...
label: statement;

In the above syntax, label is a user-defined identifier and it can be set anywhere in the C# program above or below to goto statement.

Flow Diagram:

C# goto

Example:

In the example below, the goto statement is used to display message according to provided argument.

using System;

class MyProgram {
  static void checkNaturalNumber(int x) {
    if(x < 0)
      goto notNatural;
    else if(x%2 == 0)
      goto evenNatural;
    else
      goto oddNatural;
    
    notNatural: 
      Console.WriteLine(x + " is not a natural number.");
      return;  //return when not natural
    evenNatural:
      Console.WriteLine(x + " is an even natural number.");
      return;  //return when even natural
    oddNatural:
      Console.WriteLine(x + " is an odd natural number.");
      return;  //return when odd natural
  }

  static void Main(string[] args) {
    checkNaturalNumber(10);
    checkNaturalNumber(13);
    checkNaturalNumber(-10);
  }
}

The output of the above code will be:

10 is an even natural number.
13 is an odd natural number.
-10 is not a natural number.

5