In previous article, I mentioned Int to Enum or Enum to Int in C# but in this article, I have mentioned how we can create switch case with multiple conditions in C# using various possible ways.
Multiple switch case statements using When
in C#
We can have multiple case statements in C# using the 'when
' keyword, when
keyword is used to specify a condition inside the case label to make it a ranged case in C#. In C# 7 or above (available by default in Visual Studio 2017/.NET Framework 4.6.2), range-based switching is available.
Let's take a look at an C# Console application example, using this
using System;
namespace MultipleCase
{
internal class Program
{
static void Main(string[] args)
{
int i = 3;
switch (i)
{
case int n when (n >= 7):
Console.WriteLine($"I am 7 or above: {n}");
break;
case int n when (n >= 4 && n <= 6):
Console.WriteLine($"I am between 4 and 6: {n}");
break;
case int n when (n <= 3):
Console.WriteLine($"I am 3 or less: {n}");
break;
}
}
}
}
In the above code, we are checking, if the value or 'n' is in range using when
keyword, parenthesis is not necessary but it is included to understand this code easily.
Since value of i = 3, so case 'case int n when (n <= 3):
' is executed.
Output:
I am 3 or less: 3
If you are using C# 9, you can have syntax like below
int i = 3;
switch (i)
{
case >= 7:
Console.WriteLine($"I am 7 or above: {i}");
break;
case >=4 and <= 6:
Console.WriteLine($"I am between 4 and 6: {i}");
break;
case <= 3:
Console.WriteLine($"I am 3 or less: {i}");
break;
}
The output would be the same as above.
Using Multiple Case
If you find the above code a little bit difficult to understand or if you are using C# 6 or below, you can create multiple case statements as below
using System;
namespace MultipleCase
{
internal class Program
{
static void Main(string[] args)
{
int i = 3;
switch (i)
{
case 1:
case 2:
case 3:
Console.WriteLine("Int value is between between 1 and 3");
break;
case 4:
case 5:
case 6:
Console.WriteLine("Int value is between 4 and 6");
break;
}
}
}
}
Output:
Int value is between between 1 and 3
Again, if you are using C# 9 or above, you can do the same thing as
using System;
namespace MultipleCase
{
internal class Program
{
static void Main(string[] args)
{
int i = 3;
//C# 9 or above
switch (i)
{
case 1 or 2 or 3:
Console.WriteLine("Value is from 1 - 3");
break;
case 4 or 5 or 6:
Console.WriteLine("Value is from 4 - 6");
break;
default:
Console.WriteLine("Value is above 6");
break;
}
}
}
}
Output would be
Value is from 1-3
That's it, hope this helps.
You may also like to read:
Generate Random alphanumeric strings in C#
Uncaught Error: "Cannot use import statement outside a module"