0

How should one best recode this example extension method to be generic for all numeric types?

public static float clip(this float v, float lo, float hi)
{ return Math.Max(lo, Math.Min(hi, v)); }

Thanks.

ChrisJJ
  • 2,191
  • 1
  • 25
  • 38

1 Answers1

1
// IComparable constraint for numeric types like int and float that implement IComparable
public static T clip<T>(this T v, T lo, T hi) where T : IComparable<T>
{
  // Since T implements IComparable, we can use CompareTo
  if(v.CompareTo(lo)<0)
    v=lo; // make sure v is not too low
  if(v.CompareTo(hi)>0)
    v=hi; // make sure v is not too high
  return v;
}
Peter O.
  • 32,158
  • 14
  • 82
  • 96