Evaluate Expressions in Switch Statements in C#
Note: the answer below was written in 2009. Switch patterns were introduced in C# 7.
You can't - switch/case is only for individual values. If you want to specify conditions, you need an "if":
if (num < 0)
{
...
}
else
{
switch(num)
{
case 0: // Code
case 1: // Code
case 2: // Code
...
}
}
I know that this topic is pretty old but if someone still looking for the answer now in C# 7 it's possible. Here is an example:
switch (value)
{
case var expression when value < 0:
//some code
break;
case var expression when (value >= 0 && value < 5):
//some code
break;
default:
//some code
break;
}
you can do this
switch (mark)
{
case int n when n >= 80:
Console.WriteLine("Grade is A");
break;
case int n when n >= 60:
Console.WriteLine("Grade is B");
break;
case int n when n >= 40:
Console.WriteLine("Grade is C");
break;
default:
Console.WriteLine("Grade is D");
break;
}