I would like to clamp a value x
to a range [a, b]
:
x = (x < a) ? a : ((x > b) ? b : x);
This is quite basic
If I want to validate the range of an argument in [min, max], the I use the following handy class:
public class RangeLimit<T> where T : IComparable<T>
{
public T Min { get; }
public T Max { get; }
public RangeLimit(T min, T max)
{
if (min.CompareTo(max) > 0)
throw new InvalidOperationException("invalid range");
Min = min;
Max = max;
}
public void Validate(T param)
{
if (param.CompareTo(Min) < 0 || param.CompareTo(Max) > 0)
throw new InvalidOperationException("invalid argument");
}
public T Clamp(T param) => param.CompareTo(Min) < 0 ? Min : param.CompareTo(Max) > 0 ? Max : param;
}
The class works for all object which are IComparable
. I create an instance with a certain range:
RangeLimit<int> range = new RangeLimit<int>(0, 100);
I an either validate an argument
range.Validate(value);
or clamp the argument to the range:
var v = range.Validate(value);
There isn't one, but it's not too hard to make one. I found one here: clamp
It is:
public static T Clamp<T>(T value, T max, T min)
where T : System.IComparable<T> {
T result = value;
if (value.CompareTo(max) > 0)
result = max;
if (value.CompareTo(min) < 0)
result = min;
return result;
}
And it can be used like:
int i = Clamp(12, 10, 0); -> i == 10
double d = Clamp(4.5, 10.0, 0.0); -> d == 4.5
There isn't one in the System.Math namespace.
There is a MathHelper
Class where it is available for the XNA game studio if that happens to be what you are doing: