Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two vars of T in a method of a generic class<T,U> (code port from C++ to C#)

Tags:

c#

generics

How to compare two vars of type T in a method of a generic class< T, U >? Here is an example code which throws the following compiler error:

Error CS0019 Operator '>=' cannot be applied to operands of type 'T' and 'T'

class IntervalSet< T, U >
{
    public void Add ( T start, T end, ref U val )
    {
        // new interval is empty?
        if (start >= end) // ERROR
            return; 
    }
}

I try to port source from C++ to C# and C# is new to me. Thanks for your help.

like image 365
Monotomy Avatar asked Mar 11 '23 06:03

Monotomy


1 Answers

You must tell C# that T is comparable, otherwise you can only do System.Object things with T (and that's not much), excluding creating a new instance, since C# does not even know whether T has a default constructor:

class IntervalSet< T, U >
    where T : IComparable<T>
{
    public void Add ( T start, T end, ref U val )
    {
        if (start.CompareTo(end) >= 0) {
        }
    }
}

Note that standard types like int, string, DateTime etc. all implement this interface.

See: IComparable<T> Interface,
        Constraints on Type Parameters (C# Programming Guide)

like image 63
Olivier Jacot-Descombes Avatar answered Mar 29 '23 23:03

Olivier Jacot-Descombes