In C#, the switch
statement doesn't allow cases to span ranges of values. I don't like the idea of using if-else loops for this purpose, so are there any other ways to check numeric ranges in C#?
Using range in switch case in C/C++ You all are familiar with switch case in C/C++, but did you know you can use range of numbers instead of a single number or character in case statement.
Using range in switch case in C/C++ In the switch statement we pass some value, and using different cases, we can check the value. Here we will see that we can use ranges in the case statement. After writing case, we have to put lower value, then one space, then three dots, then another space, and the higher value.
Can we test range 5 to 7 or 8 to 10 using a switch statement in C Programming ? A char variable storing either an ASCII character or a Unicode character is allowed inside switch case. We cannot use String in the Switch case as label !
You can use a HashTable
respectively Dictionary
to create a mapping of Condition => Action
.
Example:
class Programm
{
static void Main()
{
var myNum = 12;
var cases = new Dictionary<Func<int, bool>, Action>
{
{ x => x < 3 , () => Console.WriteLine("Smaller than 3") } ,
{ x => x < 30 , () => Console.WriteLine("Smaller than 30") } ,
{ x => x < 300 , () => Console.WriteLine("Smaller than 300") }
};
cases.First(kvp => kvp.Key(myNum)).Value();
}
}
This technique is a general alternative to switch
, especially if the actions consists only of one line (like a method call).
And if you're a fan of type aliases:
using Int32Condition = System.Collections.Generic.Dictionary<System.Func<System.Int32, System.Boolean>, System.Action>;
...
var cases = new Int32Condition()
{
{ x => x < 3 , () => Console.WriteLine("Smaller than 3") } ,
{ x => x < 30 , () => Console.WriteLine("Smaller than 30") } ,
{ x => x < 300 , () => Console.WriteLine("Smaller than 300") }
};
Nope. Of course, if the ranges are small you could use the
case 4:
case 5:
case 6:
// blah
break;
approach, but other than that: no. Use if
/else
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With