How do I compare values of generic types?
I have reduced it to a minimal sample:
public class Foo<T> where T : IComparable
{
private T _minimumValue = default(T);
public bool IsInRange(T value)
{
return (value >= _minimumValue); // <-- Error here
}
}
The error is:
Operator '>=' cannot be applied to operands of type 'T' and 'T'.
What on earth!? T
is already constrained to IComparable
, and even when constraining it to value types (where T: struct
), we still can't apply any of the operators <
, >
, <=
, >=
, ==
or !=
. (I know that workarounds involving Equals()
exist for ==
and !=
, but it doesn't help for the relational operators).
So, two questions:
IComparable
? Doesn't it somehow defeat the entire purpose of generic constraints?(I realize there are already a handful of questions related to this seemingly simple problem - but none of the threads gives an exhaustive or workable answer, so here.)
IComparable
doesn't overload the >=
operator. You should use
value.CompareTo(_minimumValue) >= 0