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
Written by Jerome Freyre
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#C#
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#