Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having to implement a generic less than and greater than operation

Tags:

c#

generics

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.

like image 571
Basketcase Software Avatar asked Mar 01 '10 16:03

Basketcase Software


People also ask

What is the benefit of having a generic collection?

There are many advantages to using generic collections and delegates: Type safety. Generics shift the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type because it is enforced at compile time.

How do I restrict a generic type in Java?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.

When would you use generic in your code?

Code that uses generics has many benefits over non-generic code: Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.


2 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;
}
like image 179
David Morton Avatar answered Oct 30 '22 22:10

David Morton


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.

like image 31
Marc Gravell Avatar answered Oct 30 '22 23:10

Marc Gravell