Click here to Skip to main content
Rate this: bad
good
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 20:56pm
Edited 17-Dec-12 21:19pm
lukeer15.2K
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 at 18-Dec-12 3:15am
   
Nice. The only down side I can think of, is code readability and maintainability.
Aarti Meswania at 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 at 18-Dec-12 2:28am
   
Switch case not allow this it is only match constant.
neeraj@max at 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 at 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 at 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 at 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
0 OriginalGriff 476
1 Sergey Alexandrovich Kryukov 215
2 CHill60 195
3 Afzaal Ahmad Zeeshan 145
4 TheRealSteveJudge 120
0 Sergey Alexandrovich Kryukov 9,061
1 OriginalGriff 7,920
2 Peter Leow 4,774
3 Kornfeld Eliyahu Peter 3,210
4 Maciej Los 2,176


Advertise | Privacy | Mobile
Web01 | 2.8.150327.1 | Last Updated 18 Dec 2012
Copyright © CodeProject, 1999-2015
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