C#: Switch statements and why you should use them

So currently in the game we have been crafting, we use a multi-level if-else statement to apply the powerup we collect.

This is fine for a two or three alternatives, but if we add more and more powerups we will need to add more ‘else ifs’ which can quickly get cumbersome. We can make this more tidy by changing to a Switch statement.

For a switch statement we declare the variable we are comparing our cases to then declare each possible value as a case with the resultant action should that case be true. We can add a default case to the end of the statement to catch any erroneous values.

This switch statement serves the same function as the else-ifs above but it keeps it in a more concise format and makes it easier to both read and to add to. We know at a glance that everything within the statement is relating to _powerupID without the need to read each line to confirm it.

More importantly, switch statements are generally more efficient than if-else, especially when you start talking about larger number of cases.

--

--

--

Software developer in the field of Unity and C#. Passionate about creating and always driven to develop.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

An Indepth Guide to HTML Forms

Loading Scenes in Unity

The Hero’s Journey and the 2D Game

A classic forest/woods/mountains themed tileset crafted just for you from OpenGameArt.org

PowerShell: one shell to rule them all

Everything behind the ls -la * .c command.

How we leveraged Redshift Spectrum for ELT in our land of ETL

Java developers needed in Wayne PA ($160K-210K)…

Working with Engineers For Product Manager — ‘Decoded’

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ian Plumpton

Ian Plumpton

Software developer in the field of Unity and C#. Passionate about creating and always driven to develop.

More from Medium

Making a RTS game #49: Optimisation tips & tricks (Unity/C#)

Journal 149 — Unity Project Development, 2.5D Shooter

Creating an Office Den in Unity Part 2: Lights, Cookies and Emissions

How I used scriptable objects to build a powerup system