C# goto Statement

C# goto statement is used with switch statement and loops. It transfers the control to a specified tartget in one way only. The target point is specified by a label followed by a colon.

Although C# supports goto statement, but it's rarely used. As you know that C# is a structured programming language, and the goto statement works just opposite to it.

The target label must be within the same context, it means that by using goto you cannot jump out of a function or method. The same applies for the loop and switch structure also.

Following is an example of goto with switch statement.

Example

Try It
using System;
 
namespace TutorialsLeader
{
    public class MyFirstClass
    {
        static void Main()
        {
            Console.Write("Please enter your selection between 1 and 3: ");
            string s = Console.ReadLine();
            int n = int.Parse(s);
            int Result = 0;
 
            switch (n)
            {
                case 1:
                    Result += 5;
                    break;
                case 2:
                    Result += 5;
                    goto case 1;
                case 3:
                    Result += 5;
                    goto case 2;
                default:
                    Console.WriteLine("Invalid selection.");
                    break;
            }
 
            Console.WriteLine("The result of 5*{0} is : {1}", n, Result);
        }
    }
}
Output

Please enter your selection between 1 and 3: 2
The result of 5*2 is : 10

Labled goto

Example

Try It
using System;
 
namespace TutorialsLeader
{
    public class MyFirstClass
    {
        static void Main()
        {
            Console.Write("Please enter your selection between 1 and 3: ");
            string s = Console.ReadLine();
            int n = int.Parse(s);
 
            if (n == 1)
            {
                goto One;
            }
            else if (n == 2)
            {
                goto Two;
            }
            else if (n == 3)
            {
                goto Three;
            }
            else
            {
                Console.WriteLine("Invalid selection!");
            }
 
 
        One:
            Console.WriteLine("You have entered one!");
 
        Two:
            Console.WriteLine("You have entered two!");
 
        Three:
            Console.WriteLine("You have entered three!");
        }
    }
}

Let's learn about the return statement in the next section.