C# Switch Statement vs Switch Expression Explained

There were two main switch statement patterns so far. C# 8 introduces a feature named switch expression which can use with assignment operators anywhere in the class. Yes, it can be a local, instance or static variable too.

Let’s look after the existing patterns.

1. Value Pattern (Constant Pattern)

As name explained itself, it is about data comparison of “value types”. You can define values such as integers, chars, bools and string as the case label.

C# Switch Statement: Value Pattern (Constant Pattern) Example
C# Switch Statement: Value Pattern (Constant Pattern) Example

2. Type Pattern

The type pattern is about a comparison of the instance type. It can be a user-defined instance type, C# pre-defined type, or collection type.

C# Switch Statement: Type Pattern Example
C# Switch Statement: Type Pattern Example


Case Label: Value or Type to compare against to input
Property Value: Conditions to fulfill over the input type
Case Guard: Conditions to fulfill over the input values
Case Section: Complete block including label, conditions, and statement

Switch case statement syntax: phrases and blocks explained

Switch Expression

Switch expression is a switch-like semantics that came with C# 8 which illustrates below.

Switch expression is the use of a switch case as an expression pattern. Same as the switch statements we can write both value pattern and type pattern.

In switch expressions, variable (“val” in below figures) acts as a range expression.

1. Value Pattern (Constant Pattern)

C# Switch Expression: Value Pattern (Constant Pattern) Example
C# Switch Expression: Value Pattern (Constant Pattern) Example

Pro Tip: We can’t use the “default” pattern here, instead we can use underscore (“_”).

2. Type Pattern

It’s pretty much similar to the switch statement’s type pattern. Starts with type, property conditions inside the curly braces, case guards, variable name equal, and greater than symbol statement.

C# Switch Expression: Type Pattern Example

Here {Length: 1} is an example for Property pattern. and null => “is null” is an example for Null pattern.

Using multiple patterns together is a Recursive pattern. Eg: In the above figure “Array {Length: 1} vals => ” primarily consider for type pattern and then look for Property pattern.

If we handle all types including null and underscore expression becomes exhaustive.

C# Switch expression as a statement expression

We can use a switch expression as an instance, a static and local expression body as the following method’s shorthand version.

C# Switch Expression: Statement Expression Example

Watch tutorial that explains this in 3 minutes.


Further reading