IComparable.Clamp(value,min,max)

Aug 2, 2011 at 6:49 AM

    public static class ExtensionsForIComparable
    {
        public static T Clamp<T>( this T val, T min, T max ) where T : IComparable<T>
        {
            if( val.CompareTo( min ) < 0 ) return min;
            return val.CompareTo( max ) > 0 ? max : val;
        }
    }

The benefit of this is that it does not return Boolean, just clamps the value between min and max. Sometimes, you don't care about the Boolean, just the clamped value range.