Danvil Danvil - 1 year ago 77
C# Question

Where can I find the "clamp" function in .NET?

I would like to clamp a value

to a range
[a, b]

x = (x < a) ? a : ((x > b) ? b : x);

This is quite basic. But I do not see a function "clamp" in the class library - at least not in

(For the unaware 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.)

Lee Lee
Answer Source

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;

EDIT: 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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download