Why Use Switch In C#?

Ben Pielstick
1 min readApr 8, 2021

As far as I can tell there is really no reason to use Switch apart from readability. In theory there might be some small performance gains, but if you’re hunting for those you’re probably not writing code in C# anyway. You can get the same functionality out of If / Else If as you can from Switch, and in fact If statements can do more with their conditions, so if anything If is better than Switch.

Kinda the same thing

Readability however should not be overlooked. Often times the difference between a quick simple fix and hours of work can be misreading a few lines of code. The larger your project the more likely it is for this to happen, so maintaining readability becomes more important on a project as time goes on.

So if you’re going to write a huge block of conditional statements contingent on a single index value, try and use a switch statement rather than a huge block of If / Else If. Your code probably won’t work any differently and probably won’t run noticeably faster, but you might find it easier to read in six months when you’re trying to remember why you wrote your code this way.

--

--

Ben Pielstick

Game developer with over 12 years of experience, mainly focused on MMOs.