Comparison
Provides generic methods to work with comparable values.
using System;
using System.Runtime.CompilerServices;
namespace DotNext
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public static class Comparison
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T Clamp<T>(this T value, T min, T max) where T : IComparable<T>
{
if (((IComparable<T>)value).CompareTo(min) < 0)
return min;
if (((IComparable<T>)value).CompareTo(max) > 0)
return max;
return value;
}
public static bool Between<T>(this T value, T left, T right, BoundType boundType = BoundType.Open) where T : IComparable<T>
{
switch (Math.Sign(((IComparable<T>)value).CompareTo(left)) + Math.Sign(((IComparable<T>)value).CompareTo(right))) {
case 0:
return true;
case 1:
return (boundType & BoundType.RightClosed) != BoundType.Open;
case -1:
return (boundType & BoundType.LeftClosed) != BoundType.Open;
default:
return false;
}
}
}
}