Olaf
Olaf

Reputation: 10247

Is there an elegant way to replace if by something like switch when dealing with intervals?

Is there a way in .NET to replace a code where intervals are compared like

if (compare < 10)
        {
            // Do one thing
        }
        else if (10 <= compare && compare < 20)
        {
            // Do another thing
        }
        else if (20 <= compare && compare < 30)
        {
            // Do yet another thing
        }
        else
        {
            // Do nothing
        }

by something more elegant like a switch statement (I think in Javascript "case (<10)" works, but in c#)? Does anyone else find this code is ugly as well?

Upvotes: 5

Views: 734

Answers (2)

jswolf19
jswolf19

Reputation: 2303

Since you've already affirmed that compare >= 10 after the first if, you really don't need the lower bound test on the second (or any of the other) ifs...

It's not pretty, but switch was originally implemented by hashing in C, so that it was actually faster than an if...else if chain. Such an implementation doesn't translate well to general ranges, and that's also why only constant cases were allowed.

However, for the example you give you could actually do something like:

switch(compare/10) {
    case 0:
        // Do one thing
    break;
    case 1:
        // Do another thing
    break;
    case 2:
        // Do yet another thing
    break;
    default;
        // Do nothing
    break;
}

Upvotes: 2

Justin
Justin

Reputation: 6711

One simplification: since these are all else-if instead of just if, you don't need to check the negation of the previous conditions. I.e., this is equivalent to your code:

if (compare < 10)
{
    // Do one thing
}
else if (compare < 20)
{
    // Do another thing
}
else if (compare < 30)
{
    // Do yet another thing
}
else
{
    // Do nothing
}

Upvotes: 4

Related Questions