Interface covariance problem

The following code example:

interface I<out T> where T : class, I<T> { T GetT(); } interface J : I<J> { } abstract class B<T> : I<T> where T : B<T> { T I<T>.GetT() { return null; } } class C : B<C>, J { } 

cannot compile (under VS2010 SP1) with the following error:

 Error 4 'C' does not implement interface member 'I<J>.GetT()' 

However, C implements (through its base B <C>) I <C>, which, due to the fact that I am declared covariant, must capture I <J> as well (as C: J).

Is this a compiler error? If not, why am I not allowed to do this?

+5
source share
1 answer

Even if it is covariant, you cannot change the return type of the interface. This is no different from covariance in non-general classes.

 interface Animal { Animal GetAnimal(); } class Cat : Animal { //Not ALlowed Cat GetAnimal() { return this; } //Allowed Animal GetAnimal() { return this; } } 

The problem is that C, as a specialization of B<C> returns C I<C>.GetT() , but J GetT() is required for the J specification.

Try the following:

 interface I<out T> where T : class, I<T> { T GetT(); } interface J : I<J> { } abstract class B<T,U> : I<U> where T : B<T,U>, U where U : class, I<U> { U I<U>.GetT() { return null; } } class C : B<C,J>, J { } 
+2
source

Source: https://habr.com/ru/post/890106/


All Articles