In this article, I will demonstrate C# 8 switch expressions, how to use them in our code to make them more readable, how to use them in different ways to write conditional logic, and how to leverage pattern-matching functionality using switch expressions.
Switch expressions in C#
Switch expressions in C# 8 are a valuable addition, enabling you to write cleaner and more expressive code. C# 8 switch expressions are enhanced with powerful features that can simplify your code and make it more readable and maintainable.
Syntax of Switch Expression
result = switch (expression)
{
pattern1 => expression1,
pattern2 => expression2,
pattern3 => expression3,
pattern4 => expression4,
// ...
_ => defaultExpression // This will return default value incase no pattern matches
};
- Expression: The value you want to match against patterns.
- Pattern 1, Pattern 2, Pattern 3, etc.: patterns that describe the values you want to match.
- Expression1, Expression2, Expression3, etc.: The code to execute if a pattern is matched.
- DefaultExpression: The code to execute if none of the patterns match (similar to the default case in a traditional switch statement).
What are switch expressions?
Switch expressions are a modern and highly expressive approach to writing conditional statements in C# 8. In the traditional paradigm, switch statements were constrained to basic comparisons involving constant values. In C# 8, the introduction of switch expressions, enhanced versatility, and expressiveness empower developers to write more flexible and readable code.
Benefits of Switch Expressions.
In C#8, switch expressions are a more powerful alternative to traditional switch statements. Below are the benefits of switch expressions.
- Pattern Matching
- It supports pattern matching, enabling the use of non-constant patterns in case labels. It allows developers to use various patterns, making the matching process more flexible and powerful, such as type patterns, property patterns, tuple patterns, or positional patterns.
- Code Readability
- The short and sweet syntax of switch expressions makes the code more readable and reduces static variables associated with switch statements.
- Functional Programming
- It provides a more flexible functional programming style by treating each case as an independent mapping from input to output.

Join the conversation! Your thoughts help the community grow.