C#: Switch statements and why you should use them
Switch statements are a neater and more efficient way of changing the value of a variable if you have a set number of values it might be. Here’s how 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.