I expose the following class in assembly A:
public abstract class ServiceDependencyHost
{
protected virtual T ReferenceService<T>() where T : ServiceBase
{
// Virtual implementation here...
}
}
I expose this derived class in a separate assembly (B):
public sealed class ProcessServiceOperation : ServiceDependencyHost
{
public override T ReferenceService<T>()
{
// Override implementation here...
return base.ReferenceService<T>();
}
}
Using the code as shown above, the compiler complains on this line:
return base.ReferenceService<T>();
The type 'T' cannot be used as type parameter 'T' in the generic type or method A.ReferenceService(). There is no boxing conversion or type parameter conversion from 'T' to 'System.ServiceProcess.ServiceBase'.
Naturally, I tried replicating the constraints in assembly B:
public override T ReferenceService<T>() where T : ServiceBase
But the compiler now warns on the line above...
Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly.
This answer indicates that my solution should have worked. I want to avoid using reflection to expose this method publicly. It should be so simple!
Thanks in advance to anyone who can spot what mistake I am making.
The issue is not strictly due to generics. The cause of the issue is that the base class method is protected
, whilst the derived class method is public
.
An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
Consequently, the compiler assumes that the two methods are distinct, and the derived method fails to inherit the where T : ServiceBase
generic constraint from the base method. Since the derived method knows nothing about T
, it expectedly complains that T
cannot be converted to ServiceBase
when you attempt to pass it to the base method.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments