Multiple values in one case of a switch statement in C# — how to do it correctly?
Hello everyone. I've just started learning C# and encountered a problem when using the switch statement. I need the same block of code to execute for several different values of a variable. For example, I'm writing a simple program that determines the day of the week by number (1 — Monday, 2 — Tuesday, etc.). But I need to output one message for weekends (Saturday and Sunday) and another for weekdays.
I tried writing it like this:
```csharp
int day = 6;
switch (day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
Console.WriteLine("Weekday");
break;
case 6:
case 7:
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Invalid day");
break;
}
```
This works, but I was told that in newer versions of C# there is a more elegant way. I've heard about pattern matching, but I don't understand how to apply it for multiple values. Please advise how to write such code correctly.
No answers yet.
Log in to leave an answer
Blogs
WebSockets in Rust: Building Real-Time Applications from Scratch
Advanced PHP Application Deployment on VPS: A Step-by-Step Guide
Documentation in PHP: How to Write Code You're Not Ashamed to Show
Go: How to Update Third-Party Packages in 2025 — A Complete Guide