ChrisJJ
ChrisJJ

Reputation: 2302

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

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.

Upvotes: 0

Views: 112

Answers (1)

Peter O.
Peter O.

Reputation: 32878

// 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;
}

Upvotes: 1

Related Questions