tags:

views:

121

answers:

3

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.

+7  A: 

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;
}
David Morton
+1  A: 

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:

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>.

Eamon Nerbonne
+4  A: 

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.

Marc Gravell
What are -ve and +ve?
Gabe
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
@gabe: they are a shorthand way of writing "positive" and "negative".
Eric Lippert
It seems like `<0` and `>0` are both shorter and more intuitive.
Gabe