Are you suffering from multiple uses of if-then-else statements for a particular system?
Then use a switch statement!
They are efficient, cleaner, easier to code, and easier to read.
From the Mircosoft C# Documentation, it describes the switch:
switchis 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.
When to use a Switch?
Use them when you have if-then-else chains in your code.
Take this for example. This will work. It’s a bit messy and inefficient. It’s also a chain of if-then-else statements that can grow.
if(_powerupType == PowerupType.TripleShot)
else if(_powerupType == PowerupType.Speed)
else if(_powerupType == PowerupType.Shield)
Debug.Log("A powerup has not been selected");
switch. It’s cleaner and efficient and works equally the same from the above example — replacing the if-else construct. Easier to code and read!
_powerupType = PowerupType.None;
I am using an
enum to distinguish the type of powerup. I use it for a
switch statement that allows me to have individual functionality when using the
case clauses. I then choose the powerup type ending with a colon.
The following step is to use the body of the
case clause for the functionality of the type ending with a
For more information about switch’s, head over to Microsoft’s C# Documentation!
There is a lot to learn using a
That is all for today! Thank you for reading!