Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 776
Olaf Avatar asked Mar 18 '11 14:03

Olaf


1 Answers

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
}
like image 196
Justin Avatar answered Oct 01 '22 23:10

Justin