More about C# Switch Statement in Unity

When there is a need to check an expression against different values to perform different game logic, most Unity C# developers will agree that Switch Statements, in general, is preferable to a large chains of If-Else Statements.

However, there is a few details that you need to be aware of:

Matching String expression:

Switching on String, in the worst case, have to look at every character of the string, so it can be costly in term of execution. If possible, try to switch using Integer instead:

Computer processors have machine-level instructions that can perform Integer comparison in one cycle.

What expression can you switch

For C# version up to 6.0, it can be a bool, a char, a string, an integral value (such as a long or an int) or an enum value.

For C# version 7.0 onwards, you can also use any non-null expression as a match expression.

You can check the C# version you are using in Unity Manual:

No fall-through to another case

While some other languages allow case fall-through. C# do not allow it and will through error.

Stop the flow after each case

You need to make sure control flow for each case ends with, break, return, or throw an exception

Allowed Case Labels

In C# Version 6, only constants values are allowed as case labels:

The use of a variable as case label won’t compile.

Mutually exclusive Case label values

In the above, the case label value 0 is repeated. It will not compile.

These are the most common details we need be aware of in order to use the Switch statement effectively. Thanks for reading.

A senior software engineer determined to be one of the industry's best Unity developer in 2D, 3D and VR