Where can I find the "clamp" function in .NET?
Try:
public static int Clamp(int value, int min, int max)
{
return (value < min) ? min : (value > max) ? max : value;
}
You could write an extension method:
public static T Clamp<T>(this T val, T min, T max) where T : IComparable<T>
{
if (val.CompareTo(min) < 0) return min;
else if(val.CompareTo(max) > 0) return max;
else return val;
}
Extension methods go in static classes - since this is quite a low-level function, it should probably go in some core namespace in your project. You can then use the method in any code file that contains a using directive for the namespace e.g.
using Core.ExtensionMethods
int i = 4.Clamp(1, 3);
.NET Core 2.0
Starting with .NET Core 2.0 System.Math
now has a Clamp
method that can be used instead:
using System;
int i = Math.Clamp(4, 1, 3);
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
Just use Math.Min
and Math.Max
:
x = Math.Min(Math.Max(x, a), b);