Click here to Skip to main content
12,450,981 members (55,974 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C# .NET
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.
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 17-Dec-12 19:56pm
Updated 17-Dec-12 20:19pm
lukeer16.6K
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

example
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.
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!
Smile | :)
  Permalink  
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! :)
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

That's plainly not possible. case[^] can check for equality with a constant, no more.
Stay with ifs.
  Permalink  
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160826.1 | Last Updated 18 Dec 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100