Reputation: 708
I have a covariant interface and generic class that is unrelated. I'd like the covariant interface to have a property that is an instance of that generic class on the covariant type, like so.
public interface IFoo<out T>
{
Bar<T> barobj { get; set; }
}
public class Bar<T>
{
}
Unfortunately I'm getting an error
Error CS1961 Invalid variance: The type parameter 'T' must be invariantly valid on 'IFoo<T>.barobj'. 'T' is covariant.
Does this mean that it's impossible to have a covariant interface with a generic type that uses the covariant type as the parameter? Am I doing something wrong here?
Upvotes: 0
Views: 230
Reputation: 152626
An interface can only be covariant if it only allows outputs of the generic type. Your interface is not covariant because you can set the value of barobj
. If you make the property read-only, then it can be covariant if barobj
is covariant. So that means you need a covariant interface for Bar
:
public interface IFoo<out T>
{
IBar<T> barobj { get; }
}
public class Bar<T> : IBar<T>
{
}
public interface IBar<out T>
{
}
Upvotes: 2