   [.net] Generic Extensions and Value Types?
  I'm playing around with some extensions I wrote, trying to figure out a way to consolidate all my overloads (one for each numeric type) into a single generic extension.  I started with something like this:public static T Clamp<T>(this T value, T min, T max)    where T : ValueType{    if (value is ValueType)    {   ValueType v = (ValueType)value;    if ((ValueType)min > (ValueType)max)   throw new InvalidOperationException("min must be less than or equal to max.");    if (value < min)   return min;    else if (value > max)   return max;    else   return value;}As you can see it's not finished, but clearly this isn't the right direction because "T : ValueType" isn't valid.  Even if it were, ValueType doesn't support the less-than or greater-than operators.  My questions are, is it possible to write generic extensions for value types, and if so, how?  Thanks in advance for any help.   
Quote:My questions are, is it possible to write generic extensions for value types, and if so, how?static T M<T>(this T value, ... ) where T : struct {  ...}That does not address the issue of using operators, which you cannot use with generic parameter types since there is no way to provide a constraint that assures their existence at runtime.   ;Quote:Original post by jpetrieThat does not address the issue of using operators, which you cannot use with generic parameter types since there is no way to provide a constraint that assures their existence at runtime.Which is super lame, if I say so myself. I don't think C# 4 fixes it, either.   ;  Lack of operator constraints is extra lame (and, indeed, not fixed in C# 4.0). Partial workaround here.;  While the lack of operator constraints is indeed lamentable, in this particular situation they are not needed. Observe:public static T Clamp<T>(this T value, T min, T max) where T : IComparable{    if (value.CompareTo(max) >= 0)   return max;    if (value.CompareTo(min) <= 0)   return min;    return value;};  Very nice!  This even works for types beyond the basic value types.  Great solution, thanks, Mike.   ;  What Mike suggestion is something people often fail to realize is possible to use when doing stuff like this. While it would be nice to be able to put operator constraints on a generic type, keep in mind that there are quite a few interfaces attached to basic value types. Refer to the Object Browser if you need to see them all.   ;  Just note that calling a method through an interface may cause boxing:// No boxing, fastvoid Foo<T>(T x, T y) where T : struct, IComparable<T>{    if (x.CompareTo(y) == 0)    { ... }}// Causes boxing, allocates memory, slowvoid Foo<T>(IComparable<T> x, IComparable<T> y) where T : struct{    if (x.CompareTo(y) == 0)    { ... }}