Search code examples
c#.netgenericsrefactoring

Add type constraints on generic class that extends a parent and implements interfaces


In the class hierarchy below, how to define type constraint for T (where T : class, new())?

abstract class AbstractComponent<T> : Parent, IComponentType, IRelationship
{}

class ChildComponent : AbstractComponent<CarComponent>
{}

Solution

  • It's not clear what you mean by

    In the class hierarchy below, how to define type constraint for T (where T : class, new())?

    while you could simply add where T : class, new() but if you having trouble with figuring out where to put where T : class, new() it should be something like this:

    abstract class AbstractComponent<T> : Parent, IComponentType, IRelationship
    where T : class, new() {}