'switch' in C#

On Eric's blog, a discussion about 'switch' statements in C# & why they require 'break' inspired this post.

One of my favorite principles in the design of C# is that it forces you to be explicit when that removes confusion. The best example is the way that the language doesn't let you accidentally override a base method. If you don't explicitly say what you want, the compiler tells you about it.

In this case, the language is forcing you to be explicit again. Either you're done ("break") or you want to fall through ("goto"). You gotta say which one.


I don't worry too much about the syntax of 'switch' when I code. Instead, I try to have as few 'switch' statements as possible.

The OO way to do things is to use polymorphism to manage differences between cases, not a big decision statement. As soon as I find that I'm switching on the same thing twice, it's time to consider polymorphism. See ReplaceTypeCode*.

And the procedural way is to give each option a name (make them new methods). If I have a switch where the bodies of the cases get even slightly interesting, the whole switch gets out of control. So, at the very least, I want to Extract Method on each body.

In the ideal, I have relatively few switches with only trivial content.

We did something in Whidbey to help switch lovers. We’ll generate cases from an enum.

1. Type ‘switch’.

2. Hit TAB.
This will expand a code snippet with the skeleton of a switch statement. The expression to switch on will be highlighted as an entry field.

3. Supply your favorite enum-typed variable.

4. ENTER (to commit the expansion)

We spit out a ‘case’ block for each value in the enum.

We could have done more. We could have automatically spit out ‘break;’ as soon as you type case. I think that would have made people’s concerns about the superfluous ‘break’ in C# go away. When the editor takes care of it for you, it’s not a big deal. Maybe next time.

In general, I think it’s important that the language designers think about the editing context. If you intend your language to be edited “dumb” editor (like notepad), a semi-intelligent one (emacs, slickedit), or a very intelligent one (VS, eclipse), you would design differently. If you assume certain facilities in the editor, you can take advantage of them to make the language easier to read & easier to write.