If I have this example interface:
public class BaseReq { }
public class BaseResp { }
public interface IService<in TReq, out TResp>
where TReq : BaseReq
where TResp : BaseResp
{
// Methods
// ...
}
And I have two "types" of this service that I implement as derived interfaces:
public class TypeAReq : BaseReq { }
public class TypeAResp : BaseResp { }
public interface IServiceTypeA : IService<TypeAReq, TypeAResp> { }
public class TypeBReq : BaseReq { }
public class TypeBResp : BaseResp { }
public interface IServiceTypeB : IService<TypeBReq, TypeBResp> { }
Lastly, if I attempt to assign to a variable that should be assignable to both interfaces:
IServiceTypeA GetTypeAService() { ... }
IServiceTypeB GetTypeBService() { ... }
void Run()
{
IService<BaseReq, BaseResp> myService = someFlag
? GetTypeAService()
: GetTypeBService();
}
I get an error saying:
Cannot implicitly convert type
IService<TypeAReq, TypeAResp>
toIService<BaseReq, BaseResp>
. An explicit conversion exists (are you missing a cast?)
And if I attempt to cast it, ReSharper warns me by saying:
Suspicious cast: there is no type that inherits from both
IService<TypeAReq, TypeAResp>
andIService<BaseReq, BaseResp>
.
What am I missing or doing wrong? Shouldn't the types be castable because they inherit from the base classes?