Click here to Skip to main content
15,917,628 members
Please Sign up or sign in to vote.
3.00/5 (3 votes)
See more:
i am trying to use switch case instead of If Else statement, in which i have to first check lentgh of string and as per that i have to make cases of it.
C#
Switch (mystring.lentgh)
{
    case <=25:
    {
        //do this
        break;
    }
    case <50
    {
        //d0 this
        break;
    }
    default:
    break;
}

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

thankx in advance.
Posted
Updated 17-Dec-12 20:19pm
v2

example
C#
int i = 1;
switch (i)
{
   case 0: MessageBox.Show("Hello, this is 0"); break;
   case 1:
   case 2: MessageBox.Show("Hello, this is 1 and 2 block"); break;
}



or use some trick like below...
e.g.
C#
Switch (Math.Floor((mystring.lentgh - 1)/25))
{
    case 0://for <=25
    {
        //do this
        break;
    }
    case 1://for <=50
    {
        //d0 this
        break;
    }
    default:
    break;
}


Happy Coding!
:)
 
Share this answer
 
v3
Comments
Kim Togo 18-Dec-12 3:15am    
Nice. The only down side I can think of, is code readability and maintainability.
Aarti Meswania 18-Dec-12 3:22am    
thank you! :)
That's plainly not possible. case[^] can check for equality with a constant, no more.
Stay with ifs.
 
Share this answer
 
v2
Comments
Sachin Gargava 18-Dec-12 2:28am    
Switch case not allow this it is only match constant.
neeraj@max 18-Dec-12 2:45am    
@lukeer: it is possible... there is a workaround for it.... why dont you check @Aarti's code .... :)
@Sachin Gargava: yes i know.. but being a developer we can make thing possible.. right... !!! :D
lukeer 18-Dec-12 3:15am    
You mean the one that is simply a maintenance horror?
OP should keep its ifs. They are much more readable.
neeraj@max 18-Dec-12 4:01am    
i did not said that this is good solution. i am saying this is a workaround.
ofcourse "If" is beetr then swicth in particular case.
Kim Togo 18-Dec-12 3:12am    
Correct - Case statement has to be a constant expression.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900