The Switch Statements — Unity C#

Imran Momin
3 min readApr 16, 2021

--

If-else statements are a great way to write decision logic. However, when you have more than three or four branching actions, they just aren’t feasible. Switch statements take in expressions and let us write out actions for each possible outcome, but in a much more concise format than if-else.

Basic Syntax

Switch statements require the following elements:

· A switch keyword followed by a pair of parentheses holding its condition.

· A pair of curly brackets.

· A case statement for each possible path ending with a colon. (Individual lines of code or methods, followed by the break keyword and a semicolon)

· A default case statement ending with a colon. (Individual lines of code or methods, followed by the break keyword and a semicolon)

switch (matchExpression)
{
case
matchValue1:
Executing code block
break;
case matchValue2:
Executing code block
break;
default:
Executing code block
break;
}

Pattern matching

In switch statements, pattern matching refers to how a match expression is validated against multiple case statements. A match expression can be of any type that isn’t null or nothing; all case statement values need to match the type of the match expression. For example, if we had a switch statement that was evaluating an integer variable, each case statement would need to specify an integer value for it to check against. The case statement with a value that matches the expression is the one that is executed. If no case is matched, the default case fires.

Choosing an action — Example

Since characterAction is set to Attack, the switch statement executes the second case and prints out its debug log.

Fall-through cases

Switch statements can execute the same action for multiple cases, similar to how we specified several conditions in a single if statement. The term for this is called fall-through cases.

If a case block is left empty or has code without a break keyword, it will fall through to the case directly beneath it.

Rolling the dice — Example

With diceRoll set to 7, the switch will march with the first case, which will fall through and execute case 15 because it lacks a code block and a break statement.

--

--

Imran Momin

A VR/AR developer, who enjoys making games and developing interactive environments using Unity’s XR integration toolkit for Oculus quest and HTC vive devices.