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
source share