I have the following class relationships
public interface ICapability
{
}
public interface IBaseService<T> where T : ICapability
{
}
public abstract class BaseService<out T> : IBaseService<T> where T : ICapability
{
// modified...
T MapEventToCapability(dynamic eventData, T capability);
}
public class SomeCapability : ICapability
{
}
public partial class Service1 : BaseService<SomeCapability>
{
public Service1()
{
}
}
public class ServiceResolver
{
public void Register(BaseService<ICapability> serviceToRegister)
{
}
}
I try to invoke the Register method, passing in a new service1 as shown:
var b = new ServiceResolver();
var c = new Service1();
b.Register(c);
However I get a compile time error on c in the call to Register as follows;
Cannot convert Service1 to BaseService<ICapability>
I assumed that because Service1 is of type BaseService and that since SomeCapability is of type ICapability that this wouldn’t be an issue.
I tried casting to BaseService as well I tried changing the input parameter on Register to be an IBaseService and again casting but then I get a runtime error.
>Solution :
Note the question has been updated since this answer was posted – covariance is no longer an option having added a method which is incompatible
You’ll need to do 2 things to make this work
- Make
RegistertakeIBaseService<ICapability>notBaseService<ICapability> - Make
IBaseServicecovariant by marking the generic type asout– this is the same as the reason you can pass aList<Foo>to a merthod which expects anIEnumerable<Foo>asIEnumerable<T>is covariant in a similar manner.
public class ServiceResolver
{
public void Register(IBaseService<ICapability> serviceToRegister)
{
}
}
and
public interface IBaseService<out T>
where T : ICapability
{
}
Live example: https://dotnetfiddle.net/O0yXa5