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

  1. In production code I would simply write

    1 <= x && x <= 100

    This is easy to understand and very readable.

  2. 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 as in x is >= 1 && x is <= 100

  3. 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
    

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'"

Tags:

C#

Int

Numbers