Welcome to mycodebit.com. In this article, we will discuss Multiple Cases of Switch Expression for same result in C# that have the same results. We will combine cases in switch statements in relational patterns and constant patterns. In the relational pattern we will compare expression results to the constant and with the constant pattern, we will test if the constant is equal to the expression result.
If you want to increase your productivity as a .NET developer check this post.
Click Me
I have listed some examples to understand techniques to combine case statements.
Ordinary Switch Statement to get Same Results:
Multiple cases with the same results in an ordinary switch statement by omitting the break to get the same results.
public static void MultipleCaseResults(int input) { string output; switch (input) { case 30: case 40: case 50: output = "How may I help you?"; break; case 60: output = "Oh my gosh!!"; break; default: output = "Is annoying by the way."; break; } Console.WriteLine(output); }
If the input will be (30,40,50) the output/result will be the same “How may I help you?”.
Using the when Keyword with Relational and Logical Operators
Use of “when” Keyword with Relational and Logical Operators:
By using the “when” keyword we can apply a condition into the case block while creating switch expressions with multiple cases.
public static void UsewhenMultipleCases(int input) { switch (input) { case int x when (x >= 200 && x <= 300): Console.WriteLine("The value is between 200 and 300"); break; case int n when (n >= 400 && n <= 500): Console.WriteLine("The value is between 400 and 500"); break; default: Console.WriteLine("The number is not within the specific range."); break; } }
In this example, we are using when keyword into the case block to get the same results for the multiple inputs without using multiple case blocks. As you can see we will get the same result output “The value is between 200 and 300” if the input will be any between 200 to 300.
Contains Method in Switch Statement:
We can use contains method to check if the prior defined array has the specific value to return the same result.
public static void MultipleCaseWithListValues(int input) { var list = new List<int> { 30, 40, 50 }; var output = input switch { var x when list.Contains(x) => "How may I help you?", 60 => "Oh my gosh!!", 70 => "Is annoying by the way.", _ => "No way", }; Console.WriteLine($"{output} - result when using a specific list"); }
Now let’s see a similar example using Pattern matching improvement in C# 9.0.
public static void MultipleCasePatternmatching(int input) { var output = input switch { 30 or 40 or 50 => "How may I help you?", 60 => "Oh my gosh!!", 70 => "Is annoying by the way.", > 80 => "No way", _ => "Some dummy text.", }; Console.WriteLine($"{output} pattern matching in C# 9.0");
I’m using here disjunctive “or” pattern. we can also use the conjunctive “and” pattern as well if required.
What is a switch expression?
Switch expression is a powerful feature in C# that allows developers to write more concise and efficient code. It is a type of control flow statement that is used to perform different actions based on the value of a single variable or expression. The syntax of a switch expression is similar to that of a switch statement, but with some key differences.
To use a switch expression, you start by specifying the variable or expression that you want to test. This is followed by the keyword ‘switch’ and then a set of curly braces that contain a list of ‘case’ statements. Each case statement specifies a value that you want to test the variable or expression against.
If the variable or expression matches the value in a case statement, the corresponding code block is executed. If no match is found, you can provide a default code block that is executed as a fallback.
One key difference between a switch expression and a switch statement is that a switch expression returns a value, whereas a switch statement does not. This means that you can use a switch expression in places where you need to return a value, such as in a method or property.
Another difference is that switch expressions can be used with more complex types than just integers, such as strings or enums. This allows for more flexible and expressive code that is easier to read and maintain.
Multiple cases of switch expression for the same result
Multiple cases of switch expression for the same result refer to the situation where several case statements in a switch expression lead to the same result. This can occur when you have different values that should be handled in the same way, such as different strings that should all map to the same output.
For example, imagine you are building an application that determines the level of a customer based on their total purchases. You could use a switch expression to handle the different purchase ranges and return the corresponding customer level:
string customerLevel = totalPurchases switch
{
<= 1000 => “Bronze”,
<= 5000 => “Silver”,
<= 10000 => “Gold”,
_ => “Platinum”
};
In this case, if the totalPurchases are less than or equal to 1000, the customer level is set to “Bronze”. If they are less than or equal to 5000, it’s set to “Silver”. If they are less than or equal to 10000, it’s set to “Gold”. Finally, if the totalPurchases are greater than 10000, it’s set to “Platinum”.
However, what if you want to treat some purchase ranges in the same way? For example, what if you want to consider customers who have made purchases between $1001 and $2000 as either “Bronze” or “Silver”? In this case, you could add multiple cases that lead to the same result:
string customerLevel = totalPurchases switch
{
<= 1000 => “Bronze”,
<= 2000 => “Silver”,
<= 5000 => “Gold”,
_ => “Platinum”
};
Now, if the totalPurchases are less than or equal to 1000, the customer level is set to “Bronze”. If they are less than or equal to 2000, it’s set to “Silver”. If they are less than or equal to 5000, it’s set to “Gold”. Finally, if the totalPurchases are greater than 5000, it’s set to “Platinum”.
Using multiple cases of switch expression for the same result can make your code more concise and easier to read, as you are avoiding duplication of code. However, it’s important to use this technique carefully and avoid unintended side effects or maintenance issues.
Benefits of using multiple cases of switch expression for the same result
Using multiple cases of switch expression for the same result can offer several benefits when used appropriately.
First and foremost, it can make your code more concise and easier to read. By mapping multiple cases to the same result, you are avoiding code duplication, which can make the code more compact and more readable. This can also make your code more maintainable in the long run, as you have fewer lines of code to maintain and fewer opportunities for errors to be introduced.
In addition, using multiple cases of switch expression for the same result can also lead to more efficient code. Since multiple cases are being mapped to the same result, the switch expression can skip over certain cases and go straight to the result, avoiding unnecessary computations.
Using multiple cases of switch expression for the same result can also lead to more expressive code. By mapping similar cases to the same result, you are conveying the intent of the code more clearly, making it easier for other developers to understand what the code is doing.
Finally, using multiple cases of switch expression for the same result can also help reduce code redundancy. This can make your code more modular and easier to maintain, as changes only need to be made in one place rather than being scattered throughout the codebase.
However, it’s important to use multiple cases of switch expression for the same result judiciously, as overusing this technique can lead to code that is difficult to understand or maintain. It’s important to strike a balance between using this technique to make your code more concise and avoiding excessive code complexity.
Drawbacks of using multiple cases of switch expression for the same result
While using multiple cases of switch expression for the same result can offer benefits, there are also some potential drawbacks to consider.
One potential drawback is that it can make your code less maintainable if not used judiciously. If multiple cases are mapped to the same result, it can be difficult to determine which cases are associated with which result. This can make it challenging for other developers to understand the code and make changes in the future.
Another potential issue is that using multiple cases of switch expression for the same result can introduce unexpected bugs. If you accidentally map a case to the wrong result, or forget to include a case that should be mapped to the same result, you can introduce subtle errors that can be difficult to catch.
Using multiple cases of switch expression for the same result can also lead to more complex code. If you have many cases that are mapped to the same result, the switch expression can become difficult to read and understand, making it harder to maintain in the long run.
Finally, using multiple cases of switch expression for the same result can make your code less flexible. If you later need to change the behavior of one of the cases that is mapped to the same result, you will need to update all of the cases that are associated with that result, which can be time-consuming and error-prone.
Best practices for using multiple cases of switch expression for the same result
When using multiple cases of switch expression for the same result, there are some best practices that can help you avoid potential issues and ensure that your code remains maintainable.
First, it’s important to limit the number of cases that are mapped to the same result. If you have too many cases that map to the same result, it can make the code harder to read and maintain. Instead, try to identify the most common cases that should be mapped to the same result, and keep the number of cases to a minimum.
Second, it’s important to be consistent with your use of multiple cases. If you use multiple cases in one switch expression, make sure that you use them consistently throughout your codebase. This can make it easier for other developers to understand your code and make changes in the future.
Third, it’s a good idea to use descriptive names for your cases. If multiple cases are mapped to the same result, it can be difficult to understand the intent of the code if the cases are not named appropriately. By using descriptive names, you can make the intent of the code more clear and easier to understand.
Fourth, it’s important to test your code thoroughly to ensure that it works as expected. This is especially important if you are using multiple cases of switch expression for the same result, as it can be more difficult to catch errors if you have multiple cases that are mapped to the same result.
Finally, it’s important to document your code appropriately. If you are using multiple cases of switch expression for the same result, make sure that you document the intent of the code and how it works. This can make it easier for other developers to understand your code and make changes in the future.
Additional considerations when using switch expressions
When using switch expressions in C#, there are some additional considerations that you should keep in mind to ensure that your code is efficient and effective.
First, it’s important to be mindful of performance considerations when using switch expressions. While switch expressions can be more efficient than if-else statements, they can still have a performance impact, especially if you have a large number of cases or complex logic. Consider using other control flow statements, such as if-else statements or lookup tables, if performance is a concern.
Second, it’s important to compare switch expressions to if-else statements to determine which one is the best choice for a given scenario. In general, switch expressions are more concise and easier to read for scenarios with many options, while if-else statements can be more flexible for handling complex logic. However, there are trade-offs to consider in terms of readability, maintainability, and performance.
Third, it’s important to handle null values appropriately in switch expressions. If the variable or expression being tested is null, the switch expression will throw a NullReferenceException. To avoid this, you can use the null-coalescing operator (??) to provide a default value in case the variable is null.
Finally, it’s important to understand the differences between switch expressions and switch statements. While they have similar syntax, switch statements can have side effects, as each case statement can contain arbitrary code. Switch expressions, on the other hand, can only return a value, which can make them more predictable and less error-prone.
Examples of using multiple cases of switch expressions for the same result
There are many examples of using multiple cases of switch expressions for the same result in C#, depending on the specific scenario you are working with. Here are a few examples to give you an idea of how this technique can be used:
Handling dates
If you are working with dates, you can use switch expressions to handle different date ranges that map to the same result. For example, you could use multiple cases to map different months to the same season:
string season = month switch
{
12 or 1 or 2 => “Winter”,
3 or 4 or 5 => “Spring”,
6 or 7 or 8 => “Summer”,
9 or 10 or 11 => “Fall”,
_ => throw new ArgumentException(“Invalid month.”)
};
Handling times
If you are working with times, you can use switch expressions to handle different time ranges that map to the same result. For example, you could use multiple cases to map different hours to the same time of day:
string timeOfDay = hour switch
{
>= 5 and < 12 => “Morning”,
>= 12 and < 18 => “Afternoon”,
>= 18 and < 22 => “Evening”,
_ => “Night”
};
Refactoring code
If you have existing code that uses if-else statements to handle different scenarios, you can refactor the code to use switch expressions with multiple cases. For example, consider the following code that uses if-else statements to handle different credit card types:
if (cardType == “Visa” || cardType == “MasterCard” || cardType == “Discover”)
{
// handle Visa, MasterCard, and Discover cards
}
else if (cardType == “American Express”)
{
// handle American Express cards
}
else
{
// handle other types of cards
}
This code can be refactored to use switch expressions with multiple cases:
switch (cardType)
{
case “Visa”:
case “MasterCard”:
case “Discover”:
// handle Visa, MasterCard, and Discover cards
break;
case “American Express”:
// handle American Express cards
break;
default:
// handle other types of cards
break;
}
These are just a few examples of how multiple cases of switch expressions can be used in C#. The key is to identify scenarios where you have different values that should be handled in the same way, and use multiple cases to map them to the same result. This can make your code more concise, more efficient, and easier to read and maintain.
Conclusion
In this article, we have learned some different techniques if we want to return the same output for multiple cases in a switch statement. If you have any suggestions to make our post better we are open to accepting your comments and you can also contact us.