#176 – Switch Statement Doesn’t Fall Through from Case to Case
December 10, 2010 1 Comment
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.