A generic clamp function for C#

By mikemccabe

My first C# generic function.

In computer terms, to clamp a value is to make sure that it lies between some maximum and minimum values. If it’s greater than the max value, then it’s replaced by the max, etc. I first learned it in the context of computer graphics, for colors – it’s used for instance to make sure that your raytraced pixel isn’t ‘blacker than black’. So:

    public static T Clamp<T>(T Value, T Max, T Min)
         where T : System.IComparable<T> {
        if (Value.CompareTo(Max) > 0)
            return Max;
        if (Value.CompareTo(Min) < 0)
            return Min;
        return Value;
    }

(Comments about multiple return values will be forwarded to the circular file.)

Tags: , , ,

Leave a Reply