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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With