Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary comparison operators on generic types

Tags:

c#

.net

generics

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.

like image 296
Brian Triplett Avatar asked Mar 31 '10 19:03

Brian Triplett


People also ask

What is the comparison operator in SQL?

Comparison operators are binary operators that test a condition and return 1 if that condition is logically true and 0 if that condition is false . The relational operator expressions have the form

How are the values of the operands compared after conversion?

the values of the operands after conversion are compared in the usual mathematical sense (except that positive and negative zeroes compare equal and any comparison involving a NaN value returns zero) Note that complex and imaginary numbers cannot be compared with these operators.

What happens if both operands have arithmetic types?

if both operands have arithmetic types, usual arithmetic conversions are performed and the resulting values are compared in the usual mathematical sense (except that positive and negative zeroes compare equal and any comparison involving a NaN value, including equality with itself, returns zero).

What are equality operator Expressions in C++?

The equality operator expressions have the form The type of any equality operator expression is int, and its value (which is not an lvalue) is 1 when the specified relationship holds true and ​0​ when the specified relationship does not hold.


1 Answers

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.

like image 186
Tomas Petricek Avatar answered Oct 20 '22 23:10

Tomas Petricek