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

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