Evaluate Expressions in Switch Statements in C#
I have to implement the following in a switch
statement:
switch(num)
{
case 4:
// some code ;
break;
case 3:
// some code ;
break;
case 0:
// some code ;
break;
case < 0:
// some code ;
break;
}
Is it possible to have the switch statement evaluate case < 0
? If not, how could I do that?
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;
}
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
...
}
}
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;
}