Microsoft .NET Code Analysis: Use the Switch Expressions Instead of Statements

Switch expressions were introduced in .NET Core 3 and have quickly become the recommended approach for implementing switch statements, thanks to their numerous advantages. Let’s consider the following example of a switch statement:

public enum DayOfWeek
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

public string GetDayOfWeekName(DayOfWeek dayOfWeek)
{
    string dayName;
    
    switch (dayOfWeek)
    {
        case DayOfWeek.Monday:
            dayName = "Monday";
            break;
        case DayOfWeek.Tuesday:
            dayName = "Tuesday";
            break;
        case DayOfWeek.Wednesday:
            dayName = "Wednesday";
            break;
        case DayOfWeek.Thursday:
            dayName = "Thursday";
            break;
        case DayOfWeek.Friday:
            dayName = "Friday";
            break;
        case DayOfWeek.Saturday:
            dayName = "Saturday";
            break;
        case DayOfWeek.Sunday:
            dayName = "Sunday";
            break;
        default:
            dayName = "Invalid day";
            break;
    }
    
    return dayName;
}

While the conventional switch statement syntax has been widely used by developers since the beginning of .NET, a more modern and concise approach is available through switch expressions. By embracing switch expressions, we can refactor the code as shown below:

public string GetDayOfWeekName(DayOfWeek dayOfWeek)
{
    string dayName = dayOfWeek switch
    {
        DayOfWeek.Monday => "Monday",
        DayOfWeek.Tuesday => "Tuesday",
        DayOfWeek.Wednesday => "Wednesday",
        DayOfWeek.Thursday => "Thursday",
        DayOfWeek.Friday => "Friday",
        DayOfWeek.Saturday => "Saturday",
        DayOfWeek.Sunday => "Sunday",
        _ => "Invalid day"
    };
    
    return dayName;
}

This approach is significantly cleaner and more streamlined. One notable advantage of switch expressions is the elimination of the need to add break statements. In the past, it was common to overlook or accidentally omit breaks in switch statements, leading to build errors. However, with switch expressions, this concern is eliminated. The benefits of using switch expressions include the following:

  1. Conciseness and Readability: Switch expressions are more concise and expressive compared to switch statements. They allow you to write compact code, reducing unnecessary boilerplate and making the code more readable.
  2. Expression Evaluation: Unlike switch statements, switch expressions are evaluated as expressions, meaning they can be assigned to variables or used as part of larger expressions. This makes them more versatile and enables you to use them in a wider range of scenarios.
  3. Pattern Matching: Switch expressions support pattern matching, which allows you to match against different patterns, such as types, properties, or conditions. This enables more flexible and powerful matching capabilities, making it easier to handle complex scenarios.
  4. Return Value: Switch expressions can directly return a value, making them ideal for assigning the result of a match to a variable or returning it from a method. This eliminates the need for temporary variables or additional branching logic.
  5. Exhaustiveness Checking: Switch expressions provide exhaustiveness checking by ensuring that all possible cases are handled. The compiler can detect if you’ve missed any cases or if there are redundant cases, helping you write more robust and error-free code.
  6. Scope Isolation: Switch expressions introduce scope isolation, which means that each case can have its own variables. This reduces naming conflicts and allows you to define variables specific to each case without polluting the outer scope.
  7. Refactoring and Maintainability: Switch expressions make code refactoring and maintenance easier. When you need to add or modify cases, you can do so without affecting the rest of the switch expression or introducing potential bugs in unrelated code.

When I setup the IDE0066 code analysis in my .editorConfig it looks like this: dotnet_diagnostic.IDE0066.severity = warning

Summary

During my review of the codebase for this article, I identified a significant number of 41 instances where this issue occurs. Considering the magnitude of the refactoring required, it is essential to streamline the process. Tools like CodeRush from DevExpress offer valuable extensions that simplify the refactoring task to a single mouse click, making the process efficient and convenient.

For further guidance and insights, I highly recommend obtaining a copy of my book, “Rock Your Code: Coding Standards for Microsoft .NET” available on Amazon.com. Additionally, to explore more performance tips for .NET, I encourage you to acquire the 3rd edition of “Rock Your Code: Code & App Performance for Microsoft .NET” also available on Amazon.com.

To analyze your code using the same settings I used in these articles, I encourage you to incorporate my EditorConfig file. It can be found at the following link: https://bit.ly/dotNetDaveEditorConfig. I update this file quarterly, so remember to keep yours up to date as well. I hope you will check out my OSS project Spargine by using this link: https://bit.ly/Spargine.

Please feel free to leave a comment below. I would appreciate hearing your thoughts and feedback.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.