Skip to content

C# switch statement

I’ve been meaning to write something about multi-way branching (aka switch statements) for a while. I don’t have the time now to go into everything I want to say but I’ll dip my toe into the waters by discussing the C# switch statement.

C# has a switch statement just like the one found in C/C++ and Java. But the C# switch has an important difference: it does not allow fall-through between cases. Unintentional fall-through is a common programming error so this was done to “protect” programmers from this error. Good idea but it turns out that C# does actually allow explicit fall-through by using a new form of goto statement. You can write something like this:

switch (i) {
case 0:
goto case 1;
case 1:
goto default;

Yuck! What a language wart. It reminds me of the Pascal goto statement whereby you have to declare the goto label in the prologue of the procedure to use it. (Apparently the label statement is intended as a badge of shame that you had sunk to using a goto statement). I don’t encourage the use of gotos in any language but that’s my point. If you want to disallow fall-through, just do it. Don’t come up with some extended goto syntax to let someone rattle around inside the switch block. The designers would have been better off adding a do-not-break statement to note the fall-though.

The C programming language is an excellent portable high-level assembly language. It was designed primarily as a system programming language. I’ve been writing C code for 20 years so I find C syntax to be comfortable. But do new languages have to swallow everything from C? Java doesn’t have C-style pointers and doesn’t allow any code to exist outside of classes. C# tries to improve the switch by disallowing fall-through and then adds this junk. I guess someone really wants to see an Obfuscated Programming Contest for C#.

Posted in Programming.

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

or, reply to this post via trackback.