Home  /  Questions  /  Question

56   94.9
Mar 29, 2011

Do you feel guilty when using a C# switch statement?

Now that I am familiar with Design Patterns I am beginning to feel guilty whenever I use the C# switch statement.  It is almost like switches are a 'code smell' and that a better solution is possible -- typically that would be a State or Factory Design Pattern.

Am I the only one having this guilt feeling or is it just me?
Also, am I justified to see the C# switch as a code-smell or is there still a place for this construct?

1,128   99.9
Mar 29, 2011
I believe it's good thing that if you use/see a switch statement, consider if there are better alternatives using Strategy, State, or Factory. As I believe that using those patterns will make your code more robust and easier to maintain and change.

However, not all situations require patterns. As with switch statements, sometimes it would be easier to use the switch statements instead of implementing a full-blown pattern. I guess it depends on the situation and more specifically if you anticipate that the switch statement would be changed in the future (added conditionals, etc). Bare in mind that most often, when you use patterns, your code will become more complex and you should consider if it is worth it.

It is always a trade off :)
Good Luck