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.
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.
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.
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.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With