We help IT Professionals succeed at work.

cannot convert from 'T' to 'sbyte' using Generics

rschaaf asked
Medium Priority
Last Modified: 2008-02-01
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);
Watch Question

Math.Min has many overloaded methods but all accepts number type parameters.
When compiling your generic function, the compiler doesn't know the type T. There is no way to compile this.

Try this:

static public T GetMin<T>(T a, T b) where T : IComparable
            if (a.CompareTo(b) <= 0)
                return a;
                return b;

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

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.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.