I absolutely CANNOT hard code a data type. I need strict data typing. I have to use TValue a <= TValue b. Again, there is ABSOLUTELY NO way to do something like (double) a. This is part of an essential library implementation. The only thing that is specific about the generic values is that they are of static types. IComparable and other interfaces don't seem to work.
-
8You gave a +1 whilst also admitting you don't know what the question was? :-) – Dan Puzey Mar 01 '10 at 17:13
3 Answers
Why doesn't IComparable work for you?
You may not get the syntactic sugar of using the "<" and ">" symbols, but you can check to see if the result of CompareTo is less than or greater than 0, which gives you the same information.
You could even write a nice extension method to make it easier to work with.
static void Main(string[] args)
{
Console.WriteLine(1.IsGreaterThan(2));
Console.WriteLine(1.IsLessThan(2));
}
public static bool IsGreaterThan<T>(this T value, T other) where T : IComparable
{
return value.CompareTo(other) > 0;
}
public static bool IsLessThan<T>(this T value, T other) where T : IComparable
{
return value.CompareTo(other) < 0;
}

- 16,338
- 3
- 63
- 73
-
2
-
Building generic classes about ranges of values, this is pure gold. Thanks ! – Karl Stephen Dec 17 '21 at 19:34
Just use System.Collections.Generic.Comparer<T>.Default.Compare(x,y)
- and look for negative, positive and 0 return values.
This supports both IComparable<T>
and IComparable
, and works for classes, structs and Nullable<T>
-of-structs.

- 178,213
- 47
- 333
- 501

- 1,026,079
- 266
- 2,566
- 2,900
-
That seems to do the trick. I'm using Visual Studio Express 2010 Beta, and Intellisense didn't seem to recognize this situation. Very odd behavior. – Basketcase Software Mar 01 '10 at 18:00
-
3@gabe: they are a shorthand way of writing "positive" and "negative". – Eric Lippert Mar 01 '10 at 18:25
-
12
Can you be more precise with your data type(s) and use case?
After all, to implement a comparison operation you will need some sort of information on the class; a fully generic implementation generally wonn't have the information needed to compare two objects - unless you want to sort them on GetHashCode() or ToString(), which is quite an odd thing to do.
There are various generic interfaces intended for type-safe comparison:
IComparable<T>
on the objects themselvesIComparer<T>
as an external comparison implementation.
If you've implemented IComparable
or IComparable<T>
on your type, then you can use Comparer<T>.Default
to get the latter variant automatically - which makes comparison consumers a little shorter to write, and is an alternative for a generic constraint requiring the type to be IComparable<T>
.

- 47,023
- 20
- 101
- 166
-
1+1 for explaining what `Comparer
.Default` does, and when that is useful. – ToolmakerSteve Oct 23 '14 at 18:58