A generic clamp function for C#

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: , , ,

3 Responses to “A generic clamp function for C#”

  1. Mitch Says:

    so, in beginner’s term, it would be:

    float clamp(float value, float min, float max){

    float result;

    if (value max) {result = max;}
    else {result = value;}

    return result;
    }

    correct?

    • Mitch Says:

      whoa, not what i typed:

      float clamp(float value, float min, float max){

      float result;

      if (value (greater) max) {result = max;}
      if (value (lesser) min) {result = min;}
      else {result = value;}

      return result;
      }

      PS this is C++, i just now realized your post is C#.

  2. Math Programming Short: ClampAngle & Clamp Generic implementation « Immersive Says:

    […] pancakes, but Mike Cabe has a cool code snippet with the same Clamp function as a generic, meaning that it can be used on […]

Leave a comment