Something like this:

switch (val) { case -1...1: 

2 answers 2

You cannot write a range, but you can simulate it in this way by specifying several cases for one block:

 switch (number) { case 1: case 2: case 3: case 4: case 5: //... break; case 6: case 7: case 8: case 9: case 10: //... break; } 

Perhaps in C # 7, the ability to record ranges has appeared, but I have no way to check.

    Use the alternative switch - ifElse

    Or do it as an example:

     int mynumbercheck = 1000; 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!... } }; 

    Call

     myswitch.First(sw => sw.Key(mynumbercheck)).Value(); 
    • 7
      Dictionary does not guarantee the storage and enumeration of values ​​in the order in which they were added to it. Those. The behavior of the code from your example is undefined. If you want predictable behavior, you should use List<KeyValuePair<Func<int, bool>, Action>> / List<Tuple<Func<int, bool>, Action>> - PashaPash
    • How is this better than the if - else if series? - Pavel Mayorov