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

后端 未结 27 2153
挽巷
挽巷 2020-11-27 11:17

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

27条回答
  •  暖寄归人
    2020-11-27 12:05

    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.

提交回复
热议问题