Simplify Your Code with Switch Expressions: Patterns and Examples

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.

  1. 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.
  2. Code Readability
    • The short and sweet syntax of switch expressions makes the code more readable and reduces static variables associated with switch statements.
  3. Functional Programming
    • It provides a more flexible functional programming style by treating each case as an independent mapping from input to output.

Example of Switch statement traditional approach

// Main Method 
public static void Main(String[] args) 
{ 
    string dayOfWeek = "Monday"; 

    switch (dayOfWeek) 
    { 
        case "Monday": 
            Console.WriteLine("Weekend over and new week started"); 
            break; 

        case "Tuesday": 
            Console.WriteLine("Second day of the week."); 
            break; 

        case "Wednesday": 
            Console.WriteLine("We are in the middle of the week."); 
            break; 

        case "Thursday": 
            Console.WriteLine("It's Thursdays"); 
            break; 

        case "Friday": 
            Console.WriteLine("The day before weekend !!! Fun on Friday"); 
            break; 

        default: 
            Console.WriteLine("Chill... It's the weekend!"); 
            break; 
    } 
} 

Example of Switch Expression in C# 8

using System;

class Program
{
    static void Main()
    {
        string dayOfWeek = "Monday";

        string result = dayOfWeek switch
        {
            "Monday" => "Weekend over and new week started",
            "Tuesday" => "Second day of the week.",
            "Wednesday" => "We are in the middle of the week.",
            "Thursday" => "It's Thursdays",
            "Friday" => "The day before weekend !!! Fun on Friday",
            _ => "It's the weekend!",
        };

        Console.WriteLine(result);
    }
}

In the above example, I have used the switch expression to assign the result of the switch case to the result variable. The => operator separates the case labels from the corresponding expressions. The _=> is used as a catch-all case that is not matched to the above expression, similar to the default in a traditional switch statement.

Summary 

In this article, we have learned that switch expressions in C# 8 provide a more flexible way of writing switch cases, which provides a powerful way to express complex control flow. It supports pattern matching and single-expression value assignment, making it a powerful addition to C#.

If you would like to refer to my other article, please refer to the below links.

  1. How To Export Data In EXCEL, PDF, CSV, Word, JSON, XML, And Text File In MVC Application
  2. Difference Between IQueryable, IEnumerable, And IList In LINQ
  3. LINQ Extension Methods
  4. Implement Lazy Loading In MVC
  5. Swagger UI Integration With Web API For Testing And Documentation


Similar Articles