How to compare values of generic types?
Solution 1:
IComparable
doesn't overload the >=
operator. You should use
value.CompareTo(_minimumValue) >= 0
Solution 2:
If value
can be null the current answer could fail. Use something like this instead:
Comparer<T>.Default.Compare(value, _minimumValue) >= 0
Solution 3:
Problem with operator overloading
Unfortunately, interfaces cannot contain overloaded operators. Try typing this in your compiler:
public interface IInequalityComaparable<T>
{
bool operator >(T lhs, T rhs);
bool operator >=(T lhs, T rhs);
bool operator <(T lhs, T rhs);
bool operator <=(T lhs, T rhs);
}
I don't know why they didn't allow this, but I'm guessing it complicated the language definition, and would be hard for users to implement correctly.
Either that, or the designers didn't like the potential for abuse. For example, imagine doing a >=
compare on a class MagicMrMeow
. Or even on a class Matrix<T>
. What does the result mean about the two values?; Especially when there could be an ambiguity?
The official work-around
Since the above interface isn't legal, we have the IComparable<T>
interface to work around the problem. It implements no operators, and exposes only one method, int CompareTo(T other);
See http://msdn.microsoft.com/en-us/library/4d7sx9hd.aspx
The int
result is actually a tri-bit, or a tri-nary (similar to a Boolean
, but with three states). This table explains the meaning of the results:
Value Meaning
Less than zero This object is less than
the object specified by the CompareTo method.
Zero This object is equal to the method parameter.
Greater than zero This object is greater than the method parameter.
Using the work-around
In order to do the equivalent of value >= _minimumValue
, you must instead write:
value.CompareTo(_minimumValue) >= 0
Solution 4:
public bool IsInRange(T value)
{
return (value.CompareTo(_minimumValue) >= 0);
}
When working with IComparable generics, all less than/greater than operators need to be converted to calls to CompareTo. Whatever operator you would use, keep the values being compared in the same order, and compare against zero. ( x <op> y
becomes x.CompareTo(y) <op> 0
, where <op>
is >
, >=
, etc.)
Also, I'd recommend that the generic constraint you use be where T : IComparable<T>
. IComparable by itself means that the object can be compared against anything, comparing an object against others of the same type is probably more appropriate.