In C# 8.0, a new form of “switch” was introduced. While similar, you’ll find that this new “switch expression” is more concise than it’s “switch statement” counterpart as it does not require all the various keywords (case
, break
, default
, etc.).
Take this, albeit a contrived, example, starting with this enum of car makes in our pretend application:
With that enum, we can create a specific “car manufacturing service”. Before C# 8.0, that would have looked something like this:
In C# 8.0, we can make this a little more concise, and, in my opinion, easier to read:
This new expression has a few syntax improvements, such as:
- The variable comes BEFORE the
switch
keyword. This is a sure sign you’re looking at an expression, instead of the statement. - The
case
and:
are gone, in favor of=>
, which is more intuitive. - The discard variable,
_
, replaces thedefault
case we’re used to seeing. - Finally, the bodies are expressions themselves, instead of statements.
Let me know what you think about this new (and improved!) way of writing switch stateme…expressions in the comments!
This post, “C# 8.0 - Switch Expressions”, first appeared at https://www.codingwithcalvin.net/c-8-switch-expressions
This post, "C# 8.0 - Switch Expressions", first appeared on https://www.codingwithcalvin.net/c-8-switch-expressions/