Trivial but useful extension method

Published 30 September 08 04:34 PM | Avi Pilosof 

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

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# brilsmurf said on September 30, 2008 2:36 AM:

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;

 else

   return value;

}

# Avi Pilosof said on September 30, 2008 3:23 AM:

Yep, even better!

Leave a Comment

(required) 
(optional)
(required) 

About Avi Pilosof

I'm a dev living in Sydney, working for Redmond - the best of both worlds :) My team writes applications (mostly web) used internally within MS.
Page view tracker