The Switch vs If-Else
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:
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.
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)
{
player.TripleShotActive();
}
else if(_powerupType == PowerupType.Speed)
{
player.SpeedBoostActive();
}
else if(_powerupType == PowerupType.Shield)
{
player.ShieldActive();
}
else
{
Debug.Log("A powerup has not been selected");
}
Here’s a 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!
switch (_powerupType)
{
case PowerupType.TripleShot:
player.TripleShotActive();
break;
case PowerupType.Speed:
player.SpeedBoostActive();
break;
case PowerupType.Shield:
player.ShieldActive();
break;
default:
_powerupType = PowerupType.None;
break;
}
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 break;
statement.
For more information about switch’s, head over to Microsoft’s C# Documentation!
There is a lot to learn using a switch
statement!
That is all for today! Thank you for reading!