zflesa
Last Updated: May 04, 2016
·
455
· jfreyre
Eda1e1896d41e51856d092e01ae1dfa2

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
Say Thanks
Respond