I have an IRepository interface that inherits from IRepository<TObject>. I also have a SqlRepository class that inherits from SQLRepository<TObject>, which in turn implements IRepository<TObject>. Why can’t I instantiate a instance of SqlRepository as an IRepository?
public class MyObject : IObject {
...
}
public interface IRepository<TObject> where TObject : IObject, new() {
...
}
public interface IRepository : IRepository<MyObject> { }
public class SqlRepository<TObject> : IRepository<TObject> where TObject : IObject, new() {
...
}
public class SqlRepository : SqlRepository<MyObject> { }
public class Controller {
private IRepository _repository;
public Controller() {
_repository = new SqlRepository();
}
}
The example above fails when trying to assign a new SqlRepository to _repository in the Controller class, with the following error message.
Argument '1': cannot convert from 'SqlRepository' to 'IRepository'
Which basic principle of inheritance have I failed to grasp, please help.
Because
IRepositoryis anIRepository<MyObject>and not the other way around.Basically:
SqlRepositoryis aSqlRepository<MyObject>which is an
IRepository<MyObject>.To make that work, you should either inherit
IRepository<TObject>fromIRepositoryor makeSqlRepositoryimplementIRepositorydepending in your intention.This issue is not generics-specific at all. Assume:
It’s obvious that
Ballis not anIDrivablewhile it is anIMovable.