How to elegantly check if a number is within a range?

There are a lot of options:

int x = 30;
if (Enumerable.Range(1,100).Contains(x))  //true

And indeed basic if more elegantly can be written with reversing order in the first check:

if (1 <= x && x <= 100)   //true

Also, check out this SO post for regex options.

Notes:

  • LINQ solution is strictly for style points - since Contains iterates over all items its complexity is O(range_size) and not O(1) normally expected from a range check.
    More generic version for other ranges (notice that second argument is count, not end):

    if (Enumerable.Range(start, end - start + 1).Contains(x)
    
  • There is temptation to write if solution without && like 1 <= x <= 100 - that look really elegant, but in C# leads to a syntax error "Operator '<=' cannot be applied to operands of type 'bool' and 'int'"


Do you mean?

if(number >= 1 && number <= 100)

or

bool TestRange (int numberToCheck, int bottom, int top)
{
  return (numberToCheck >= bottom && numberToCheck <= top);
}

In production code I would simply write

1 <= x && x <= 100

This is easy to understand and very readable.

Starting with C#9.0 we can write

x is >= 1 and <= 100
// Note that we must write x only once. "is" introduces a pattern matching
// expression where "and" is part of the pattern.
// "&&" would require us to repeat "x is": x is >= 1 && x is <= 100

Here is a clever method that reduces the number of comparisons from two to one by using some math. The idea is that one of the two factors becomes negative if the number lies outside of the range and zero if the number is equal to one of the bounds:

If the bounds are inclusive:

(x - 1) * (100 - x) >= 0

or

(x - min) * (max - x) >= 0

If the bounds are exclusive:

(x - 1) * (100 - x) > 0

or

(x - min) * (max - x) > 0

Just to add to the noise here, you could create an extension method:

public static bool IsWithin(this int value, int minimum, int maximum)
{
    return value >= minimum && value <= maximum;
}

Which would let you do something like...

int val = 15;

bool foo = val.IsWithin(5,20);

That being said, this seems like a silly thing to do when the check itself is only one line.