Shakti Prakash Singh
Shakti Prakash Singh

Reputation: 2533

Convert if 'with range' to switch statement

Someone asked me today how to convert the following if statement to switch:

int i=5;
if(i>10)
{
   Do Something;
}
else
{
    Do Something else;
}

And I proposed that assuming i is an integer with only positive values:

int i=5;
switch(i)
{
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
    case 8:
    case 9:
    case 10: Do Something else;
    break;
    case default: Do Something;
    break;
}

Is there any other, more elegant way of doing it?

Upvotes: 0

Views: 1159

Answers (2)

Sepster
Sepster

Reputation: 4849

First, note your two code examples (as were originally written) were not equivalent:

  • You're not Do[ing] Something Else when i==10 in your switch example.
  • But the original if code was checking on i>10 (as opposed to i>=10).
  • So case 10: should be explicitly included in your list of cases that fall through to Do Something Else.

To answer your question, I believe in some languages (eg pascal, objective C, I think?) a range similar to this is allowed:

switch(i)
{
    case 1-10: // or is it "case 1 .. 10" ?
        Do Something else;
        break;
    case default: 
        Do Something;
        break;
}

But this is not supported in C#. Refer the very final point in the code discussion regarding "stacking" of case labels here MSDN switch(C#)

Upvotes: 1

Habib
Habib

Reputation: 223282

There is no direct way of doing that in C#, you can try the following.

int range = (number - 1) / 10;

switch(range)
{
  case 0: 
       Console.WriteLine("1 to 10");
       break;
  case 1:
       Console.WriteLine("11 to 20");
       break;
 //.,......
  default:
       break;
}

Not really sure how much clear it would be, IMO, the above approach would reduce the code readability, its better if you use if-else for the range checking. Also the above would work only if the range is constant.

Upvotes: 1

Related Questions