unitytips: Switch Expressions

Unity started to supporting C# 8.0 with version 2020.2 beta and now we can start to use some new features like the Switch Expression.

post image


Introduction

Switch Expressions can dramatically simplify and reduce the LOC (Lines Of Code) to make a switch.

The switch expression provides for switch-like semantics in an expression context. It provides a concise syntax when the switch arms produce a value.

Often, a switch statement produces a value in each of its case blocks. Switch expressions enable you to use more concise expression syntax. There are fewer repetitive case and break keywords, and fewer curly braces.

Sample

Classic switch

In the code below we have a classic switch statement:

Switch expression

And we can reduce 7 lines of code of this simple switch statement using a switch expression:

Visual Studio tip

If you are using Visual Studio, there is a Quick action (CTRL + .) to convert from a classic switch to a switch expression:

post image


Loading comments...
Tutorials

Articles

Labs