Advertisement
Guest User

Constraint a value (e.g. a number) to a range in C#

a guest
Jan 25th, 2022
630
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. /// <summary>
  2. /// Provides extension methods for the <see cref="IComparable{T}"/> type.
  3. /// </summary>
  4. public static class ComparableExtensions
  5. {
  6.     /// <summary>
  7.     /// Constraints <paramref name="value" /> to the lower bound <paramref name="min" /> and the upper bound <paramref name="max" />.
  8.     /// If <paramref name="value" /> is less than <paramref name="min" />, <paramref name="min" /> is returned.
  9.     /// If <paramref name="value" /> is greater than <paramref name="max" />, <paramref name="max" /> is returned.
  10.     /// Otherwise, <paramref name="value"/> is returned.
  11.     /// </summary>
  12.     /// <typeparam name="T">The type of <paramref name="value"/>.</typeparam>
  13.     /// <param name="value">The value to constrain.</param>
  14.     /// <param name="min">The lower bound to constrain <paramref name="value" /> to.</param>
  15.     /// <param name="max">The upper bound to constrain <paramref name="value" /> to.</param>
  16.     /// <returns><paramref name="value" /> constraint to the specified bounds.</returns>
  17.     /// <exception cref="ArgumentOutOfRangeException"><paramref name="min"/> is greater than <paramref name="max"/>.</exception>
  18.     public static T ConstrainToRange<T>(this T value, T min, T max)
  19.         where T : notnull, IComparable<T>
  20.     {
  21.         if (min.CompareTo(max) > 0)
  22.         {
  23.             var minString = Convert.ToString(min, CultureInfo.InvariantCulture);
  24.             var maxString = Convert.ToString(max, CultureInfo.InvariantCulture);
  25.             throw new ArgumentOutOfRangeException(nameof(min), $"The argument {nameof(min)} ({minString}) must not be greater than the argument {nameof(max)} ({maxString}).");
  26.         }
  27.  
  28.         return value.CompareTo(min) < 0 ? min : value.CompareTo(max) > 0 ? max : value;
  29.     }
  30. }
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement