Today, while doing some research in the MSDN Library, I came across an interesting use of C#’s goto statement. Instead of causing the application’s execution to jump to a named label—a practice frowned upon in the programming world—this example used goto to emulate C/C++’s switch statement’s fall through behavior.
The C++ Way
In the following C++ example, if Quantity equals 3, the case 3 condition will be matched. Cost will have 10 added to it. Then, because there is no break statement, execution will “fall through” to the code inside the case 2 statement. Cost will have 15 added to it. Execution will then drop into the case 1 statement where Cost will again be increased, this time by 20. At the end of the switch block, Cost will have been increased by a total of 45.
switch (Quantity) { case 3: Cost += 10; case 2: Cost += 15; case 1: Cost += 20; break; }
Now, In C#
C#’s switch statement doesn’t support this fall-through behavior. Instead, the last statement in a C# switch’s case section must terminate the execution of that case section. Two examples of statements fulfilling this requirement are break or return. Another option is goto.
Using goto, it is possible to emulate the introductory C++ code’s functionality:
switch (Quantity) { case 3: Cost += 10; goto case 2; case 2: Cost += 15; goto case 1; case 1: Cost += 20; break; }
Unlike C++ where fall-through happens only in a downward direction, a C# goto case statement can refer to a case condition proceeding it (e.g. the goto in case 1 could send execution up to case 3). Also, the statement goto case default can be used to transfer execution to a switch statement’s default section.