0

In short, I'm trying to achieve this:

BaseRepository<BaseUser> repository = new DerivedRepository();
//error: Cannot implicitly convert type 'DerivedRepository' to 'BaseRepository<BaseUser>'

The long story: I'm trying to store a DerivedRepository instance in a BaseRepository. This BaseRepository is a generic class, which takes < T > as BaseUser.

I can make it work if I define my derived class this way:

class DerivedRepository: BaseRepository<BaseUser> //works, but bad for the end user

But I need it to be:

DerivedRepository: BaseRepository<DerivedUser> //ideal. But errors.

Lets see a "working" sample code:

//============================================
//bases
class BaseUser { }

interface IBaseRepository<out T> where T : BaseUser { }

class BaseRepository<T> : IBaseRepository<T> where T : BaseUser
{
}

//============================================
//derived

class DerivedUser : BaseUser { }

class DerivedRepository : BaseRepository<DerivedUser> // <-- pass if I use BaseUser. But I need Deriveduser as stated
{
    public void Test()
    {
        BaseRepository<BaseUser> repository = new DerivedRepository();
        //error: Cannot implicitly convert type 'DerivedRepository' to 'BaseRepository<BaseUser>'
    }
}

Notice I've even used used the "< out T >" above (I read other articles), but no way.

How can I set the that derived instance to it's base definition?

Cesar
  • 420
  • 6
  • 12
  • You are very close, change BaseRepository repository = new DerivedRepository() to IBaseRepository repository = new DerivedRepository() – FuriousCactus Oct 14 '21 at 17:04
  • lol tried a lot of things around it, and this option skipped me. Guess I'm tired. Thanks, if you put as an answer, I'll accept it. – Cesar Oct 14 '21 at 21:40

0 Answers0