Switch It Up: Switch Statements

Antonio Delgado
2 min readMay 3, 2021

In this article we’ll talk about switch statements, a useful tool in your toolbox. So what’s a switch statement and how does it differ from an if/else block?

Let’s go to Microsoft Docs (here) on the subject, along with the Unity Scripting API this is very helpful for getting quick (if sometimes dense) explanations on C#. “switch is a selection statement that chooses a single switch section to execute from a list of candidates based on a pattern match with the match expression.”

That seems pretty straight forward, unlike a if/else statement which uses a series of boolean checks to determine an action, a switch statement is looking single expression. An example of this would be like our modular power-up system (here) article which uses a switch statement to determine which power-up is chosen based on the PowerUpType selected and then executes the logic in it’s given match. We can see that example below, you can check the article for a practical implementation.

So why would you use these clunky if/else blocks if you have these sleek switch statements lying around making your code super readable? Easy, switch statements are really really good at making a choice between established choices. They’re less good at parsing more than a single defined expression at once like choosing an item off a menu. An example of something that it wouldn’t excel at would be a complex choice structure like enemy AI.

A switch statement can tell the enemy to enter a certain state or to do a particular piece of logic if a certain condition is hit but running through a series of checks is more unwieldy and requires some thoughtful set up. Those cases an if/else block is more useful and easier to understand.

For example if an enemy AI runs away when on fire, it can check to see if it’s on fire, if the player is in range, and where it is in relation to it’s allies creating much more complex decision making. Ultimately the best use is a blend of both to make your code as readable as possible. When in doubt use what’s most comfortable to you. Until next time, happy coding.

--

--