rschaaf
asked on
cannot convert from 'T' to 'sbyte' using Generics
Here's my function:
static public void SetMin<T>(ref T a, T b) { // Invalid - Cannot convert from'T' to sbyte
a = Math.Min(a, b);
}
Visual Studio 2005 gives the errors:
The best overloaded method match for 'System.Math.Min(sbyte, sbyte)' has some invalid arguments
Argument '1': Cannot convert from 'T' to 'sbyte'
Argument '2': Cannot convert from 'T' to 'sbyte'
Why is this? If I unwrap this method and declare directly with sbyte, the compiler is fine with it:
static public void SetMin(ref sbyte a, sbyte b) { // Works fine
a = Math.Min(a, b);
}
static public void SetMin<T>(ref T a, T b) { // Invalid - Cannot convert from'T' to sbyte
a = Math.Min(a, b);
}
Visual Studio 2005 gives the errors:
The best overloaded method match for 'System.Math.Min(sbyte, sbyte)' has some invalid arguments
Argument '1': Cannot convert from 'T' to 'sbyte'
Argument '2': Cannot convert from 'T' to 'sbyte'
Why is this? If I unwrap this method and declare directly with sbyte, the compiler is fine with it:
static public void SetMin(ref sbyte a, sbyte b) { // Works fine
a = Math.Min(a, b);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Oops, sorry for duplicated post.
Actually, it is not 100% duplicated, because I use IComparable<T> :)
True, IComparable<T> is better.
static public void SetMin<T>(ref T a, T b) where T :IComparable<T>
{
a = a.CompareTo(b) < 0 ? a : b;
}