How do you verify if a number is within a range in an elegant way?

Problem

What’s the most elegant way to accomplish this in C#?

A number can be anything between 1 and 100, for example.

I realize that a simple if (x >= 1 && x = 100) would work; but, C#/ has a lot of syntax sugar and new features are continually added. This question is about more idiomatic (i.e., elegant) ways of writing that.

Although performance is not a problem, please add a performance notice to non-O(1) solutions, as individuals may copy-paste the suggestions.

Solution #1

There are numerous solutions available to you:

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

And, yes, the first check can be stated more elegantly by reversing the order:

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

Also, for regex possibilities, see this SO post.

Notes:

Solution #2

In production code, I’d just write

``````1 <= x && x <= 100
``````

This is highly readable and easy to understand.

We can write C# code starting with version 9.0.

``````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
``````

Using basic arithmetic, this innovative solution decreases the number of comparisons from two to one. The notion is that if the number is outside of the range, one of the two factors becomes negative, and if the number is equal to one of the boundaries, the other factor becomes zero:

If the boundaries are inclusive, the following is true:

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

or

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

If the boundaries are mutually exclusive, the following is true:

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

or

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

Solution #3

Do you mean?

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

or

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

Solution #4

You might write an extension method just to add to the noise here:

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

Which would enable you to…

``````int val = 15;

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

However, when the check itself is only one line, this seems like a ridiculous thing to perform.

Solution #5

Use a simple if, as others have suggested.

Consider your options when it comes to ordering.

e.g

``````1 <= x && x <= 100
``````

``````x >= 1 && x <= 100
``````