#177 – Using goto in a switch Statement

You can use a goto statement within a switch statement to jump to another case clause.  This allows you to execute the contents of more than one case clause for a particular value of the switch expression.

            switch (day)
            {
                case DayOfWeek.Sunday:
                    Console.WriteLine("Go to church");
                    goto case DayOfWeek.Saturday;
                case DayOfWeek.Monday:
                    Console.WriteLine("Read Ulysses");
                    break;
                case DayOfWeek.Tuesday:
                    Console.WriteLine("Call Dad");
                    goto case DayOfWeek.Saturday;
                case DayOfWeek.Wednesday:
                    Console.WriteLine("Do laundry");
                    goto case DayOfWeek.Thursday;
                case DayOfWeek.Thursday:
                    Console.WriteLine("Watch a movie");
                    break;
                case DayOfWeek.Friday:
                    Console.WriteLine("Take out the trash");
                    goto case DayOfWeek.Tuesday;
                case DayOfWeek.Saturday:
                    Console.WriteLine("Relax");
                    break;
            }

This results in the following output:

  • Sunday: Go to church; Relax
  • Monday: Read Ulysses
  • Tuesday: Call Dad; Relax
  • Wednesday: Do laundry; Watch a movie
  • Thursday: Watch a movie
  • Friday: Take out the trash; Call Dad; Relax
  • Saturday: Relax

Think carefully before using goto in a switch statement.  There are often more clear ways to implement the same logic.

Advertisements