Switch case: can I use a range instead of a one number [duplicate]
Solution 1:
A bit late to the game for this question, but in recent changes introduced in C# 7 (Available by default in Visual Studio 2017/.NET Framework 4.6.2), range-based switching is now possible with the switch
statement.
Example:
int i = 63;
switch (i)
{
case int n when (n >= 100):
Console.WriteLine($"I am 100 or above: {n}");
break;
case int n when (n < 100 && n >= 50 ):
Console.WriteLine($"I am between 99 and 50: {n}");
break;
case int n when (n < 50):
Console.WriteLine($"I am less than 50: {n}");
break;
}
Notes:
- The parentheses
(
and)
are not required in thewhen
condition, but are used in this example to highlight the comparison(s). -
var
may also be used in lieu ofint
. For example:case var n when n >= 100:
.
Solution 2:
Here is a better and elegant solution for your problem statement.
int mynumbercheck = 1000;
// Your number to be checked
var myswitch = new Dictionary <Func<int,bool>, Action>
{
{ x => x < 10 , () => //Do this!... },
{ x => x < 100 , () => //Do this!... },
{ x => x < 1000 , () => //Do this!... },
{ x => x < 10000 , () => //Do this!... } ,
{ x => x < 100000 , () => //Do this!... },
{ x => x < 1000000 , () => //Do this!... }
};
Now to call our conditional switch
myswitch.First(sw => sw.Key(mynumbercheck)).Value();
Alternate for Switch/ifElse