Trivial but useful extension method

Don’t know why I didn’t write this before; it makes code very readable. Often when you write anything graphics related, you want to constrain coordinates to window edges (for example).

So a simple method:

   1: /// <summary>
   2: /// Ensure that the given number falls within the
   3: /// given min/max constraints.
   4: /// </summary>
   5: public static double Constrain( this double num,
   6:                         double min, double max )
   7: {
   8:     if (num < min)
   9:         return min;
  10:     else if (num > max)
  11:         return max;
  12:     else
  13:         return num;
  14: }

It’s just a Floor combined with a Ceiling, but it reads nicely:

   1: xform.X = dx.Constrain(-this.ActualWidth, 0 );
   2: xform.Y = dy.Constrain(-this.ActualHeight, 0 );



Comments (3)
  1. brilsmurf says:

    Nice, but why not make it generic?

    public static T Constrain<T>(this T value, T min, T max) where T : IComparable<T>


     if (value.CompareTo(min)<0)

       return min;

     else if (value.CompareTo(max)>0)

       return max;


       return value;


  2. AviP says:

    Yep, even better!

  3. Dave says:

    “It’s just a Floor combined with a Ceiling, but it reads nicely:”

    Your code dosen’t read like that, whythe ifs?

    public static int Constraint(this int value, int min, int max)


    return Math.Min(Math.Max(value,min), max);


Comments are closed.

Skip to main content