1

I need to create generic method which returns greater of two params. Operators > and < don't work. Here is signature of my method:

public static T Greater<T>(ref T a, ref T b)
{
    if (a > b) 
    {
       return a;
    }
    else 
    {
       return b;
    }
}

I'm quite rookie in C# and totally new in generic types.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Box
  • 81
  • 1
  • 1
  • 5

1 Answers1

10

Since the T can be any type there is no guarantee that T will overload > or < operators. Adding a IComparable<T> constraint you are saying that T must implement IComparable<T> which contains a method named CompareTo, then you can use that method to compare your objects instead:

public static T Greater<T>(ref T a, ref T b) where T : IComparable<T>
{
    if(a.CompareTo(b) > 0) return a;
    else return b;
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184