Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added an extension method for clamping values in C# #74

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions C#/Method Extension/Clamp.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System;

public static partial class ExtensionMethods
{
/// <summary>
/// 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.
/// </summary>
/// <typeparam name="T">The type of the value.</typeparam>
/// <param name="value">The value to clamp.</param>
/// <param name="minimumValue">The lower bound for the value.</param>
/// <param name="maximumValue">The upper bound for the value.</param>
/// <returns>
/// 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.
/// </returns>
public static T Clamp<T>(this T value, T minimumValue, T maximumValue) where T : IComparable<T>
{
if (value.CompareTo(minimumValue) < 0)
{
return minimumValue;
}
else if (value.CompareTo(maximumValue) > 0)
{
return maximumValue;
}
return value;
}
}