In this article, we are going to learn how to create a switch expression with multiple cases that have the same result.

To download the source code for this article, you can visit our GitHub repository.

We can combine the cases inside the switch statement either in a relational pattern or a constant pattern. With the relational pattern, we compare the expression result to a constant, while with a constant pattern, we test if the expression result equals a constant.

Let’s list a few ways with examples to see how we can combine those results in a single statement using a few simple techniques.

Merging Multiple Cases with the Same Results

In an ordinary switch statement, we can combine multiple case blocks together by omitting breaks in order to return the same result:

public static void SubMultipleCaseResults(int switchTemp)
{
    var resultstring = string.Empty;

    switch (switchTemp)
    {
        case 20:
        case 22:
        case 24:
            resultstring = "It is a pleasant day";
            break;
        case 30:
            resultstring = "It is very hot today";
            break;
        default:
            resultstring = "No weather report today";
            break;
    }

    Console.WriteLine(resultstring);
}

The result string "It is a pleasant day" applies to multiple cases (20, 22, 24).

Using the when Keyword with Relational and Logical Operators

While creating a switch expression with multiple cases, we can also use the when keyword to specify a condition inside the case block:

public static void SubMultipleCaseResultsWithWhen(int value)
{
    switch (value)
    {
        case int n when (n >= 50 && n <= 150):
            Console.WriteLine("The value is between 50 and 150");
            break;
        case int n when (n >= 150 && n <= 200):
            Console.WriteLine("The value is between 150 and 200");
            break;
        default:
            Console.WriteLine("The number is not within the given range.");
            break;
    }
}

In this case, we are not using multiple case blocks for the same result but rather use relational and logical operators with the when keyword to define a condition range for our result. The output depends on the value variable.

Using the Contains Method in Switch Case

We can also use the Contains extension method to specify whether a sequence contains the specified element.

To do that, we can create our own extension method, and then use it in the switch-case expression:

public static bool In<T>(this T val, params T[] vals) => vals.Contains(val);

public static void SubMultipleCaseWithExtension(int tempValue)
{
    var result = tempValue switch
    {
        var x when x.In(20, 22, 24) => "It is a pleasant day",
        30 => "It is hot today",
        35 => "It is very hot today",
        _ => "No weather report",
    };

    Console.WriteLine($"{result} - with extension method");
}

As we can see, we can use our custom In method for different types.

We can also use an array or a list instead of the extension method if we already know the type we are going to work with:

public static void SubMultipleCaseWithListValues(int tempValue)
{
    var templist = new List<int> { 20, 22, 24 };
    
    var newresult = tempValue switch
    {
      var x when templist.Contains(x) => "It is a pleasant day",
      30 => "It is hot today",
      35 => "It is very hot today",
      _ => "No weather report",
    };
    
    Console.WriteLine($"{newresult} - result when using a list");
}

Finally, we can see a similar example using the C# 9.0 pattern matching improvement:

public static void SubMultipleCaseWithNewVersion(int tempValue)
{
    var resultText = tempValue switch
    {
     20 or 22 or 24 => "It is a pleasant day",
     30 => "It is hot today",
     35 => "It is very hot today",
     > 35 => "Heat wave condition",
     _ => "No weather report.",
    };
    
    Console.WriteLine($"{resultText} result is for C# 9.0 syntax");
}

Here, we are using just the disjunctive or pattern, but of course, if we need it, we can use the conjunctive and pattern as well.

Conclusion

In this article, we have seen several simple techniques that we can use when we want to create switch statements with multiple cases that return the same result.

 

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get paid? >> JOIN US! <<