Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch case with integer expression

Tags:

c#

.net

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.

like image 469
neerajMAX Avatar asked Dec 18 '12 06:12

neerajMAX


People also ask

Can we use integer in switch-case?

A switch works with the byte , short , char , and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character , Byte , Short , and Integer (discussed in Numbers and Strings).

Can we use expression in switch-case?

1) The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed. 2) All the statements following a matching case execute until a break statement is reached. 3) The default block can be placed anywhere.

Which expression is not allowed in switch-case?

The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed.

Can we use expression in switch-case in Java?

The switch case in Java works like an if-else ladder, i.e., multiple conditions can be checked at once. Switch is provided with an expression that can be a constant or literal expression that can be evaluated. The value of the expression is matched with each test case till a match is found.


2 Answers

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;

}
like image 66
Habib Avatar answered Oct 27 '22 08:10

Habib


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;
}
like image 33
Steve Gomez Avatar answered Oct 27 '22 08:10

Steve Gomez