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

后端 未结 27 2210
挽巷
挽巷 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 11:42

    A new twist on an old favorite:

    public bool IsWithinRange(int number, int topOfRange, int bottomOfRange, bool includeBoundaries) {
        if (includeBoundaries)
            return number <= topOfRange && number >= bottomOfRange;
        return number < topOfRange && number > bottomOfRange;
    }
    

提交回复
热议问题