Search code examples
c#genericsinheritanceinterfaceconstraints

Inherit from a generic base class, apply a constraint, and implement an interface in C#


This is a syntax question. I have a generic class which is inheriting from a generic base class and is applying a constraint to one of the type parameters. I also want the derived class to implement an interface. For the life of me, I cannot seem to figure out the correct syntax.

This is what I have:

DerivedFoo<T1,T2> : ParentFoo<T1, T2> where T2 : IBar { ... }

The first thing that came to mind was this:

DerivedFoo<T1,T2> : ParentFoo<T1, T2> where T2 : IBar, IFoo { ... }

But that is incorrect as that causes T2 to need to implement both IBar and IFoo, not DerivedFoo to implement IFoo.

I've tried a bit of Googling, use of colons, semicolons, etc, but I've turned up short. I'm sure the answer is head slappingly simple.


Solution

  • You include the entire signature of your class before you define generic constraints.

    class DerivedFoo<T1, T2> : ParentFoo<T1, T2>, IFoo where T2 : IBar
    {
        ...
    }