Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch case, check ranges in C# 3.5 [duplicate]

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#?

like image 636
Kenny Avatar asked Jul 05 '12 06:07

Kenny


People also ask

Can we check range using switch case?

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.

How do you find the range of a switch case?

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?

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 !


2 Answers

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") } 
    };
like image 61
sloth Avatar answered Oct 12 '22 13:10

sloth


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.

like image 25
Marc Gravell Avatar answered Oct 12 '22 13:10

Marc Gravell