7

I have a generic class that takes a type T. Within this class I have a method were I need to compare a type T to another type T such as:

public class MyClass<T>
{
    public T MaxValue
    {
        // Implimentation for MaxValue
    }

    public T MyMethod(T argument)
    {
        if(argument > this.MaxValue)
        {
             // Then do something
        }
    }
}

The comparison operation inside of MyMethod fails with Compiler Error CS0019. Is it possible to add a constraint to T to make this work? I tried adding a where T: IComparable<T> to the class definition to no avail.

Brian Triplett
  • 3,462
  • 6
  • 35
  • 61
  • It's Impossible =( . However there is an open source math library that tries to deal with it, have to recall the name... – vittore Mar 31 '10 at 19:16

5 Answers5

9

Adding constraint to make sure that the type implements IComparable<T> is a way to go. However, you cannot use the < operator - the interface provides a method CompareTo to do the same thing:

public class MyClass<T> where T : IComparable<T> { 
    public T MaxValue  { 
        // Implimentation for MaxValue 
    } 

    public T MyMethod(T argument) { 
        if(argument.CompareTo(this.MaxValue) > 0){ 
             // Then do something 
        } 
    } 
}

If you needed other numeric operators than just comparison, the situation is more difficult, because you cannot add constraint to support for example + operator and there is no corresponding interface. Some ideas about this can be found here.

Community
  • 1
  • 1
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • Good call Tomas. I found a blog post at http://blogs.telerik.com/hristoborisov/posts/09-01-10/comparing_generic_types.aspx regarding this exact issue shortly after I asked the question that confirms what you are saying. – Brian Triplett Mar 31 '10 at 19:18
3

No, it is not possible, operator constraints are unfortunately not allowed in c#. where T: IComparable<T> should work just fine, but you have to use other semantics: CompareTo method instead of >,< and == operators.

n535
  • 4,983
  • 4
  • 23
  • 28
2

You have to use IComparable<T>'s CompareTo method.

1

Actually, you don't need anything special here. Comparer<T>.Default offers a .Compare method that will do everything you need without requiring any additional generic constraints (which tend to propagate horribly). It works for both IComparable<T> and IComparable, and supports classes, structs and Nullable<T>. Job done.

For info, this is how the LINQ Max / Min implementations work, and likewise List<T>.Sort. So a common and well supported part of the BCL.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

It is not directly possible, but there are workarounds.

I posted mine in a different question here.

Community
  • 1
  • 1
Lucero
  • 59,176
  • 9
  • 122
  • 152