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 );

 

Avi