#176 – Switch Statement Doesn’t Fall Through from Case to Case

Unlike C++, in C# you can’t force execution of a switch statement to “fall through” from one case clause to another by leaving out the break statement.  Each case clause must end with a break, goto, throw or return statement.

The following code results in a compile-time error.

            switch (carType)    // carType is a string
            {
                case "Saturn":
                    Console.WriteLine("Domestic car");
                case "Yugo":
                    Console.WriteLine("Inexpensive car");
                    break;
            }

Technically, the requirement is that the end of the statement block in a case clause must not be reachable–implying that you must transfer control out of the block, typically with a break statement.  This requirement means that it would be valid syntax to include an infinite loop in a case clause, without a break statement.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #176 – Switch Statement Doesn’t Fall Through from Case to Case

  1. Kris says:

    However, it is possible to do this:

    switch (carType) // carType is a string
    {
    case “Saturn”: // Either Saturn or Yugo
    case “Yugo”:
    Console.WriteLine(“…”);
    break;
    }

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 )

Google+ photo

You are commenting using your Google+ 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

%d bloggers like this: