Last Updated: May 04, 2016
·
3.542K
· Jérome Freyre

Clamp in c#

C# does not provide a native way to clamp value.

Here is a generic one

public static class MathHelper
{
    /// <summary>
    /// Clamping a value to be sure it lies between two values
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="aValue"></param>
    /// <param name="aMax"></param>
    /// <param name="aMin"></param>
    /// <returns></returns>
    public static T Clamp<T>(T aValue, T aMin, T aMax) where T : IComparable<T>
    {
        var _Result = aValue;
        if (aValue.CompareTo(aMax) > 0)
            _Result = aMax;
        else if (aValue.CompareTo(aMin) < 0)
            _Result = aMin;
        return _Result;
    }

} // En class