From 98de26ae1855fd7dd768141616fb347b7cfc7815 Mon Sep 17 00:00:00 2001 From: Michizev Date: Thu, 31 Oct 2019 19:13:06 +0100 Subject: [PATCH] Added an extension method for clamping values in C# --- C#/Method Extension/Clamp.cs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C#/Method Extension/Clamp.cs 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