The process to clamp a value to a range is somewhat long:
if (value < min) value = min;
else if (value > max) value = max;
Even longer when the type of your value does not implement comparison operators:
// Type of meetingDate is System.DateTime
if (meetingDate.CompareTo(startDate) < 0) meetingDate = startDate;
else if (meetingDate.CompareTo(endDate) > 0) meetingDate = endDate;
The System.Math.Clamp
method can do this operation in one line, but it only supports a limited number of primitive types. Types such as System.Version
and System.DateTime
are not supported.
ClampToRange
does this in a more intuitive, shorter and functional style friendly way:
using CLSS;
value = value.ClampToRange(min, max);
No more short stops in your code reading to decode the meanings of comparison operators. When you read ClampToRange
, you know what it's doing.
ClampToRange
has a wider range of supported types than System.Math.Clamp
. It supports all IComparable<T>
types. For non-generic IComparable
types, the equivalent method provided by this package is ClampToRangeNonGeneric
.
using CLSS;
// System.DateTime implements IComparable<T>
meetingDate = meetingDate.ClampToRange(startDate, endDate);
ClampToRange
can also take in CLSS type ValueRange
on .NET Standard 2.0 or higher.
using CLSS;
var displayableRange = new ValueRange(0, 9999);
int value = value.ClampToRange(displayableRange);