Pattern Matching and Switch Expressions

Learn how to replace verbose conditional statements with concise, functional switch expressions and advanced pattern matching.

Earlier in this course, we explored the traditional switch statement. It evaluates a variable and executes a block of code using case labels and break keywords. This is known as control flow.

The switch expression

Modern C# introduces the switch expression. Instead of executing blocks of code, a switch expression evaluates a variable and directly returns a single value. This enables a more functional style and eliminates the boilerplate associated with traditional statements.

The syntax differs structurally. In a switch expression, the variable comes before the switch keyword. The case and : keywords are replaced by the expression lambda (=>), and the default keyword is replaced by the discard pattern (_).