> I have a class that tries to compare two generic types:
>
[quoted text clipped - 10 lines]
> I tried the most general type an hope it can be cast to T but I am getting an
> error.
What if T is String or System.Windows.Form? You can't cast a floating
point value to a string or a Form, and that's why the compiler won't
accept it. Generics in C# are not like templates in C++: the generic
method definition, taken in isolation, must be type-safe itself. In C++,
the template body isn't fully type-checked until you pass it template
arguments.
If you know that only number types will be used as T, you might try
using the Convert class to perform the conversion, but you'll have to
live with the possibility of runtime errors.
> 2) This is the most baffling I am getting the error: Operator '<' cannot be
> applied to operands of type 'T' and 'T'. What "operators" are available to
> compare two generic types?
You can use Comparer<T>.Compare(T,T) to compare generic types. This will
query the types for IComparable<T> and use that if it exists (it does on
float, for example). Similarly, there is an EqualityComparer<T>.
If you want flexibility, write your method or class so that it accepts
IComparer<T> or IEqualityComparer<T>, and default to Comparer<T> /
EqualityComparer<T> if the user doesn't supply a comparer.
-- Barry

Signature
http://barrkel.blogspot.com/
Generics constraints are your friend. Pet my constraint; it won't bite:
public class GenericallyComparable<T> where T: IComparer<T> { ... }
> I have a class that tries to compare two generic types:
>
[quoted text clipped - 18 lines]
>
> Kevin
Barry Kelly - 03 Jul 2006 18:33 GMT
> Generics constraints are your friend. Pet my constraint; it won't bite:
> public class GenericallyComparable<T> where T: IComparer<T> { ... }
You'll probably want "where T : IComparable<T>" instead. Types generally
don't implement their own comparers.
-- Barry

Signature
http://barrkel.blogspot.com/