Skip to content

Instantly share code, notes, and snippets.

@ormaaj
Created December 29, 2014 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ormaaj/0704b2248b7ea30d2274 to your computer and use it in GitHub Desktop.
Save ormaaj/0704b2248b7ea30d2274 to your computer and use it in GitHub Desktop.
Generic clamp with configurable comparer
public static T Clamp<T>(this T value, T min, T max, IComparer<T> comparer = null) {
if (comparer.Equals(null))
comparer = Comparer<T>.Default;
if (comparer.Compare(value, min) <= 0) {
return min;
} else if (comparer.Compare(value, max) >= 0) {
return max;
} else {
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment