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

How can I do this elegantly with C#?

For example, a number can be between 1 and 100.

I know a simple if (x >= 1 && x <= 100) would suffice; but with a lot of syntax sugar and new features constantly added to C#/.Net this question is about more idiomatic (one can all it elegance) ways to write that.

Performance is not a concern, but please add performance note to solutions that are not O(1) as people may copy-paste the suggestions.

32 Answers
32

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

Leave a Comment