Click here to Skip to main content
Sign Up to vote bad
good
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:56
Edited 17 Dec '12 - 20:19
lukeer9.9K


2 solutions

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  
Comments
Kim Togo - 18 Dec '12 - 3:15
Nice. The only down side I can think of, is code readability and maintainability.
Aarti Meswania - 18 Dec '12 - 3:22
thank you! :)
That's plainly not possible. case[^] can check for equality with a constant, no more.
Stay with ifs.
  Permalink  
Comments
Sachin Gargava - 18 Dec '12 - 2:28
Switch case not allow this it is only match constant.
neeraj@max - 18 Dec '12 - 2:45
@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:15
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:01
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:12
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
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 464
1 Mahesh Bailwal 373
2 Maciej Los 215
3 CPallini 175
4 Rohan Leuva 175
0 Sergey Alexandrovich Kryukov 9,402
1 OriginalGriff 7,204
2 CPallini 3,933
3 Rohan Leuva 3,211
4 Maciej Los 2,743


Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 18 Dec 2012
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid