[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Understand ways to end case blocks in C#

There are several ways that you can exit case blocks in a switch statement. For example, consider the following code.

string result = ""; int control = 1; switch (control) { case 1: case 2: result = "One or two"; break; case 3: result = "Three"; for (; ; ) ; case 4: result = "Four"; while (true) ; case 5: result = "Five"; return; case 6: result = "Six"; throw new ArgumentException(); case 7: // This one isn't allowed. result = "Seven"; while (control == 7) { } }

[Understand ways to end case blocks in C#]

A switch statement contains a series of case blocks. You can place multiple case statements together in a block to make all of the cases execute the same code, but you cannot allow one block of code to fall through to the next block.

For example, in the code above cases 1 and 2 both execute the same block of code.

Most developers expect to see a break statement at the end of each case block, but there are other ways that you can end case blocks.

Usually, each block of code ends in a break statement to make execution jump out of the switch statement, but any code that prevents execution from dropping into the next block will work. As the code above demonstrates, a block can also end in an infinite for loop, an infinite while loop, a return statement, or a throw statement because all of those prevent execution from falling into the next case block.

The final case statement doesn't work because the compiler isn't smart enough to realize that the code doesn't change the value of the variable control so that loop can never end.

In fact, that block doesn't work even if you change that statement to while (true || (control == 7)) even though you can easily see that the loop can never end.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.