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.
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;
}
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>
.
Just use System.Collections.Generic.Comparer<T>.Default.Compare(x,y)
- and look for -ve, +ve and 0.
This supports both IComparable<T>
and IComparable
, and works for classes, structs and Nullable<T>
-of-structs.