开发者

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

开发者 https://www.devze.com 2022-12-11 06:08 出处:网络
I\'d like to test a variable (\"userChoice\") for the numeric val开发者_JAVA百科ues 0-32 and 99if((userChoice >= 0 && userChoice <= 32) || userChoice == 99)

I'd like to test a variable ("userChoice") for the numeric val开发者_JAVA百科ues 0-32 and 99


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


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.


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


Do you mean this?

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

精彩评论

暂无评论...
验证码 换一张
取 消