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?

Was it helpful?

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
scroll top