Solved

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

Posted on 2006-11-06
5
645 Views
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);
}
0
Comment
Question by:rschaaf
  • 3
  • 2
5 Comments
 
LVL 13

Accepted Solution

by:
joechina earned 125 total points
ID: 17881295
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;
            else
                return b;
        }
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 17881297
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;
        }
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 17881304
Oops, sorry for duplicated post.
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 17881315
Actually, it is not 100% duplicated, because I use IComparable<T> :)
0
 
LVL 13

Expert Comment

by:joechina
ID: 17881641
True, IComparable<T> is better.
0

Featured Post

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question