diff --git a/C#/Method Extension/Clamp.cs b/C#/Method Extension/Clamp.cs new file mode 100644 index 00000000..baa00c2d --- /dev/null +++ b/C#/Method Extension/Clamp.cs @@ -0,0 +1,29 @@ +using System; + +public static partial class ExtensionMethods +{ + /// + /// Compares a value to the given upper and lower bounds, in case it is not inside the bounds, it returns the upper or lower bound. + /// + /// The type of the value. + /// The value to clamp. + /// The lower bound for the value. + /// The upper bound for the value. + /// + /// Returns the original value if it is inside the bounds. + /// If it is smaller than the lower bound, it returns the lower bound. + /// If it is bigger than the upper bound, it returns the upper bound. + /// + public static T Clamp(this T value, T minimumValue, T maximumValue) where T : IComparable + { + if (value.CompareTo(minimumValue) < 0) + { + return minimumValue; + } + else if (value.CompareTo(maximumValue) > 0) + { + return maximumValue; + } + return value; + } +} \ No newline at end of file