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:
- Why do we observe this weird behaviour? What keeps us from comparing the values of generic types which are known to be
IComparable
? Doesn't it somehow defeat the entire purpose of generic constraints? - How do I resolve this, or at least work around it?
(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.)