You can check the range of values ​​in the IF expression

I would like to check a variable ("userChoice") for numeric values ​​0-32 and 99

+4
source share
4 answers
if((userChoice >= 0 && userChoice <= 32) || userChoice == 99) { // do stuff } 
+7
source

Just to add another way of thinking, when I have range tests, I like to use the Contains <T> List method. In your case, this may seem far-fetched, but it will look something like this:

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

If you worked in a simple range, this would have looked a lot cleaner:

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

What is nice is that it works great with testing a number of lines and other types without having to write || again and again.

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

Do you mean this?

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

All Articles