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

后端 未结 27 2205
挽巷
挽巷 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:48

    Elegant because it doesn't require you to determine which of the two boundary values is greater first. It also contains no branches.

    public static bool InRange(float val, float a, float b)
    {
        // Determine if val lies between a and b without first asking which is larger (a or b)
        return ( a <= val & val < b ) | ( b <= val & val < a );
    }
    

提交回复
热议问题