How can I do this elegantly with C# and .NET 3.5/4?
For example, a number can be between 1 and 100.
I know a simple if would suffice; but the keyword to this
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 have to write x only once.
// "is" introduces a pattern matching expression.
// "and" is part of the pattern matching unlike the logical "&&".
// With "&&" we would have to write: 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