How to specify type constraint and inheritance on declaring class?
-
12-12-2019 - |
Question
I've got an abstract
class which has a type constraint. But i also want to make the abstract
class implement an interface.
E.g:
public abstract class PostEvent<TPost> : IDomainEvent, where TPost : Post, new()
Which doesn't compile.
I don't want this:
public abstract class PostEvent<TPost> where TPost : Post, IDomainEvent, new()
Because that means TPost : IDomainEvent
I want PostEvent : IDomainEvent
What's the syntax?
Solution
Try this:
public abstract class PostEvent<TPost> : IDomainEvent where TPost : Post, new()
You don't want a comma between the interface list and the generic constraints.
OTHER TIPS
You need to actually implement it (you can't leave the implementation purely to the concrete types - it needs to know where to start):
public abstract class PostEvent<TPost> : IDomainEvent
where TPost : Post, new()
{
public abstract void SomeInterfaceMethod();
}
You could also use an explicit interface implementation and protected abstract method if you don't want Otis on the public API:
public abstract class PostEvent<TPost> : IDomainEvent
where TPost : Post, new()
{
protected abstract void SomeInterfaceMethod();
void IDomainEvent.SomeInterfaceMethod() {
SomeInterfaceMethod(); // proxy to the protected abstract version
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow