You don't need generics for this. While the concept of "DRY" makes the idea of coding a single function that can work for all types, this is a case where you're better off having discreet functions for each numeric type. All of the numeric types are known, and the list is not overly large; there are likely numeric types that you aren't actually going to use, anyway. If you really (for whatever reason) want a single function, then your only real option is the IComparable
option that you linked to, which has the unfortunate (and unnecessary) consequence of causing boxing on the numeric parameters.
That being said, your problem is that you cannot have T : decimal, double
, as that means that T
must be both decimal
and double
(which is impossible), not that it can be either one.
In addition, since this is all that this function does, I'd probably not call the Math.Max
and Math.Min
functions anyway. It's probably just as simple, if not slightly clearer, to write the functions this way:
public static decimal ClipGN(this decimal v, decimal lo, decimal hi)
{
return v <= lo ? lo : v >= hi ? hi : v;
}
And you should be able to duplicate this code verbatim (apart from the return and parameter types, of course) for each of the numeric types.