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

Dan Rigby picture Dan Rigby · Jan 5, 2010 · Viewed 65.8k times · Source

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.

Answer

Adam Robinson picture Adam Robinson · Jan 5, 2010

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

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