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
I propose this:
public static bool IsWithin(this T value, T minimum, T maximum) where T : IComparable {
if (value.CompareTo(minimum) < 0)
return false;
if (value.CompareTo(maximum) > 0)
return false;
return true;
}
Examples:
45.IsWithin(32, 89)
true
87.2.IsWithin(87.1, 87.15)
false
87.2.IsWithin(87.1, 87.25)
true
and of course with variables:
myvalue.IsWithin(min, max)
It's easy to read (close to human language) and works with any comparable type (integer, double, custom types...).
Having code easy to read is important because the developer will not waste "brain cycles" to understand it. In long coding sessions wasted brain cycles make developer tired earlier and prone to bug.