dhalberg
dhalberg

Reputation: 155

can you test for a range of values in an IF statement

I'd like to test a variable ("userChoice") for the numeric values 0-32 and 99

Upvotes: 6

Views: 1328

Answers (4)

t3rse
t3rse

Reputation: 10124

Just to add a different kind of thinking, when I have range tests I like to use the Contains method of List<T>. In your case it may seem contrived but it would look something like:

        List<int> options = new List<int>(Enumerable.Range(0, 33));
        options.Add(99);
        if(options.Contains(userChoice)){
            // something interesting
        }

If you were operating in the simple range, it would look much cleaner:

        if(Enumerable.Range(0, 33).Contains(userChoice)){
            // something interesting
        }

What's nice about this is that is works superbly well with testing a range of strings and other types without having to write || over and over again.

Upvotes: 7

Omar
Omar

Reputation: 40182

if((userChoice >= 0 && userChoice <= 32) || userChoice == 99)
{
     // do stuff
}

Upvotes: 8

willoller
willoller

Reputation: 7330

if((userChoice >= 0 && userChoice < 33) || userchoice  == 99) {
...
}

Upvotes: 6

llamaoo7
llamaoo7

Reputation: 4331

Do you mean this?

if (userChoice >= 0 && userChoice <= 32 || userChoice == 99)

Upvotes: 4

Related Questions