Sam
Sam

Reputation: 4339

Casting implementation to the interface with generic type

My company has a shared library that has code like this

public interface IBaseService<TBaseUser> where TBaseUser : BaseUser
{
   // snip
}

public class User : BaseUser
{
    // snip
}

public class SomeService : IBaseService<User>
{

}

Various applications make use of this shared code. I am trying to write a base controller that takes in an IBaseService<BaseUser> in its ctor.

public class BaseController : Controller
{
    public BaseController(IBaseService<BaseUser> service)
    { 
    }
}

The code at the library level works exactly as I'd expect, but when I try to use it from a consuming application and pass in the derived type, i.e. a Service type, it fails with an invalid cast.

public class MyController : BaseController
{
    public MyController(SomeService service) : base(service)
    {
    }
}

Is what I want to do possible?

Upvotes: 3

Views: 109

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

Your IBaseService-iterface needs to be covariant:

interface IBaseService<out T> 

This way you can assign an instance of IBaseService<User> to IBaseService<BaseUser>.

Upvotes: 2

Related Questions