Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 847
Sam Avatar asked Dec 27 '25 16:12

Sam


1 Answers

Your IBaseService-iterface needs to be covariant:

interface IBaseService<out T> 

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

like image 134
MakePeaceGreatAgain Avatar answered Dec 30 '25 04:12

MakePeaceGreatAgain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!