Every time I need to prevent a value from going under a minimum or going over a maximum, I have to stop and think about how to use the Math API.  If I want to supply a max value, I need to use Math.Min; and conversely, if I want to supply a min value, I need to use Math.Max.

Given int value = 5, if I want to ensure that my value has a minimum of 10, I need to call: Math.Max(value, 10).

Given int value = 500, if I want to ensure that my value has a maximum of 100, I need to call: Math.Min(value, 100).

Yes, these functions do exactly what they say, but the way I always use them makes the API seem backwards.  The other day, I decided to solve this problem once and for all.  In my scalar extensions class in my project, I added the following methods.

   1: /// <summary>
   2: /// Return a value that is no less than a minimum
   3: /// </summary>
   4: public static int ButNoLessThan(this int value, int minimum)
   5: {
   6:   return Math.Max(value, minimum);
   7: }
   9: /// <summary>
  10: /// Return a value that is no more than a maximum
  11: /// </summary>
  12: public static int ButNotMoreThan(this int value, int maximum)
  13: {
  14:   return Math.Min(value, maximum);
  15: }

Here’s a quick illustration:

   1: int small = 5;
   2: int large = 500;
   4: Console.WriteLine(small.ButNoLessThan(10));
   5: Console.WriteLine(large.ButNotMoreThan(100));
   7: Console.WriteLine((small * large).ButNoLessThan(1000).ButNotMoreThan(10000));