#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.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers