diff --git a/X10D/src/ComparableExtensions/ComparableExtensions.cs b/X10D/src/ComparableExtensions/ComparableExtensions.cs index 7948775..4861484 100644 --- a/X10D/src/ComparableExtensions/ComparableExtensions.cs +++ b/X10D/src/ComparableExtensions/ComparableExtensions.cs @@ -50,6 +50,43 @@ namespace X10D.ComparableExtensions { return actual.CompareTo(lower) > 0 && actual.CompareTo(upper) < 0; } + + /// + /// Returns the current value clamped to the inclusive range of and . + /// + /// The value to be clamped. + /// The lower bound of the result. + /// The upper bound of the result. + /// An type. + /// + /// if . + /// -or- + /// if < . + /// -or- + /// if < . + /// + /// is greater than . + /// + /// + /// int value = 42; + /// int lower = 0; + /// int upper = 20; + /// + /// int clamped = value.Clamp(lower, upper); + /// // clamped will be 20 + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T Clamp(this T value, T lower, T upper) + where T : IComparable + { + if (lower.GreaterThan(upper)) + { + throw new ArgumentException($@"{lower} cannot be greater than {upper}", nameof(lower)); + } + + return value.Max(lower).Min(upper); + } /// /// Determines if the current value is greater than another value.