How to compare values of generic types?

gstercken picture gstercken · Jun 25, 2011 · Viewed 78.9k times · Source

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:

  1. 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?
  2. 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.)

Answer

faester picture faester · Jun 25, 2011

IComparable doesn't overload the >= operator. You should use

value.CompareTo(_minimumValue) >= 0