neerajMAX
neerajMAX

Reputation: 269

switch case with integer expression

i am trying to use switch case instead of If Else statement, in which i have to first check length of string and as per that i have to make cases of it.

switch (mystring.length)
{
    case <=25:
    {
        //do this
        break;
    }
    case <50:
    {
        //do this
        break;
    }
    default:
        break;
}

This is some thing i want to do but unable to get how to put <25 in front of case because it is not appropriate as per switch case rules.

Upvotes: 14

Views: 99472

Answers (4)

Steve G
Steve G

Reputation: 13397

This really doesn't help the OP much, but hopefully it will help someone looking for this in the future.

If you're using C# 7 (Available in Visual Studio 2017), you can switch on a range.

Example:

switch (mystring.length)
{
    case int n when (n >= 0 && n <= 25):
    //do this
    break;

    case int n when (n >= 26 && n <= 50 ):
    //do this
    break;
}

Upvotes: 19

palaѕн
palaѕн

Reputation: 73926

Try this:

int range = (int) Math.Floor(mystring.Length / 25);

switch (range) {
case 0:

    //do this <= 25
    break;

case 1:

    //do this < 50 & > 25
    break;

default:
    break;
}​

Upvotes: 2

I4V
I4V

Reputation: 35363

You can not do this with switch but there may be a workaround for this.

Dictionary<int, Action> actions = new Dictionary<int, Action>()
    {
        {25,()=>Console.WriteLine("<25")},
        {49,()=>Console.WriteLine("<50")},
        {int.MaxValue,()=>Console.WriteLine("Default")},
    };


actions.First(kv => mystring.length < kv.Key).Value();

Upvotes: 2

Habib
Habib

Reputation: 223282

Its always better to use if/else for your particular case, With switch statement you can't put conditions in the case. It looks like you are checking for ranges and if the range is constant then you can try the following (if you want to use switch statement).

int Length = mystring.Length;
int range = (Length - 1) / 25;
switch (range)
{
    case 0:
        Console.WriteLine("Range between 0 to 25");
        break;
    case 1:
        Console.WriteLine("Range between 26 to 50");
        break;
    case 2:
        Console.WriteLine("Range between 51 to 75");
        break;

}

Upvotes: 22

Related Questions