s

C# goto statement edit button Edit

author
Rakesh Kumar Sutar | calendar 12 January 2021 | 2006

Introduction

The goto statement transfers the program control directly to a labeled statement. A common use of goto is to transfer control to a specific switch-case label or the default label in a switch statement. The goto statement is also useful to get out of deeply nested loops.

Example - Goto

using System;

namespace Hello_world
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");
            Console.Write("Please enter your selection: ");
            string s = Console.ReadLine();
            int n = int.Parse(s);
            int cost = 0;
            switch (n)
            {
                case 1:
                    cost  = 25;
                    break;
                case 2:
                    cost  = 25;
                    goto case 1;
                case 3:
                    cost  = 50;
                    goto case 1;
                default:
                    Console.WriteLine("Invalid selection.");
                    break;
            }
            if (cost != 0)
            {
                Console.WriteLine($"Please insert {cost} cents.");
            }
            Console.WriteLine("Thank you for your business.");

            // Keep the console open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();

        }
    }
}

Output