How to fix this error? Invalid variance: a parameter of type T must be invariant for

I get the following error message at compile time:

"Invalid variance: a parameter of type" T "must be invariant for" ConsoleApplication1.IRepository.GetAll () "." T "is covariant."

and below is my code:

class Program { static void Main(string[] args) { IRepository<BaseClass> repository; repository = new RepositoryDerived1<Derived1>(); Console.ReadLine(); } } public abstract class BaseClass { } public class Derived1 : BaseClass { } public interface IRepository<out T> where T: BaseClass, new() { IList<T> GetAll(); } public class Derived2 : BaseClass { } public abstract class RepositoryBase<T> : IRepository<T> where T: BaseClass, new() { public abstract IList<T> GetAll(); } public class RepositoryDerived1<T> : RepositoryBase<T> where T: BaseClass, new() { public override IList<T> GetAll() { throw new NotImplementedException(); } } 

What I need is to use this class as follows:

IRepository repository;

or

Repository database repository;

Then I would like to be able to assign something like this:

repository = new RepositoryDerived1 ();

But it gives a compile-time error in the IRepository class.

If I remove the "out" keyword from the IRepository class, this will give me another error, which

"RepositoryDerived1" cannot be converted to "IRepository".

Why and how to fix it?

thanks

+4
source share
1 answer

IList<T> not covariant. If you change IList<T> to IEnumerable<T> and remove the restriction : new() from IRepository<out T> (since the abstract base class does not satisfy this), it will work:

 public interface IRepository<out T> where T : BaseClass { IEnumerable<T> GetAll(); } public abstract class RepositoryBase<T> : IRepository<T> where T : BaseClass, new() { public abstract IEnumerable<T> GetAll(); } public class RepositoryDerived1<T> : RepositoryBase<T> where T : BaseClass, new() { public override IEnumerable<T> GetAll() { throw new NotImplementedException(); } } 
+4
source

All Articles