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: c#, clamp, generic, System.IComparable
July 2, 2010 at 8:08 pm |
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?
July 2, 2010 at 8:12 pm |
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#.
February 7, 2013 at 12:47 am |
[…] pancakes, but Mike Cabe has a cool code snippet with the same Clamp function as a generic, meaning that it can be used on […]