Link to home
Start Free TrialLog in
Avatar of rschaaf
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);
}
ASKER CERTIFIED SOLUTION
Avatar of joechina
joechina

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of AlexFM
AlexFM

I don't know way to do this using Math function, but this one can be used as replacement:

        static public void SetMin<T>(ref T a, T b) where T :IComparable<T>
        {
            a = a.CompareTo(b) < 0 ? a : b;
        }
Oops, sorry for duplicated post.
Actually, it is not 100% duplicated, because I use IComparable<T> :)
True, IComparable<T> is better.