3

Why the following code get the error?

Invalid variance: The type parameter 'T' must be invariantly valid on 'UserQuery.IItem<T>.GetList()'. 'T' is covariant.

public interface IFoo {}
public interface IBar<T> where T : IFoo {}

public interface IItem<out T> where T: IFoo
{
    IEnumerable<IBar<T>> GetList();
}
ca9163d9
  • 27,283
  • 64
  • 210
  • 413

2 Answers2

9

The interfaces IBar and IItem do not agree on variance: in your IBar declaration, the T is not covariant, as there is no out keyword, whereas in IITem the T is covariant.

Bartosz
  • 3,318
  • 21
  • 31
1

The following code will get rid of the error.

public interface IFoo {}
public interface IBar<out T> where T : IFoo {}

public interface IItem<out T> where T: IFoo
{
    IEnumerable<IBar<T>> GetList();
}
ca9163d9
  • 27,283
  • 64
  • 210
  • 413