Compiler complains about type constraint in generic class

G

Guest

Hi there,

I have the following class hierarchy that isn't compiling correctly, and I
don't understand why:

public abstract class A<T> where T : System.IComparable<T> { }
public abstract class B : System.IComparable<B>
{
public abstract int CompareTo(B other);
}
public abstract class C<T> : A<T> where T : B {}

The compiler (Visual Studio 2005) reports that class C has the following
error:

The type 'T' must be convertible to 'System.IComparable<T>' in order to use
it as parameter 'T' in the generic type or method 'A<T>'

I'm confused by this, because in class C, I'm constraining type T to be of
type class B, and class B is IComparable<B>. So, shouldn't class C's type T
therefore be IComparable<B>? Could someone explain why this is an error?

Thanks in advance!
 
B

Ben Voigt

Whitney Kew said:
Hi there,

I have the following class hierarchy that isn't compiling correctly, and I
don't understand why:

public abstract class A<T> where T : System.IComparable<T> { }
public abstract class B : System.IComparable<B>
{
public abstract int CompareTo(B other);
}
public abstract class C<T> : A<T> where T : B {}

The compiler (Visual Studio 2005) reports that class C has the following
error:

The type 'T' must be convertible to 'System.IComparable<T>' in order to
use
it as parameter 'T' in the generic type or method 'A<T>'

I'm confused by this, because in class C, I'm constraining type T to be of
type class B, and class B is IComparable<B>. So, shouldn't class C's type
T
therefore be IComparable<B>? Could someone explain why this is an error?

Thanks in advance!

Covariant interfaces aren't supported. And the constraint would be wrong
even if they were. Consider:

class D : B {}

D implements IComparable<B>, but not IComparable<D>. Therefore D cannot be
used as the parameter to A, so T : B is not sufficient to use A<T>.

Add a second type parameter to A:

 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top