Search code examples
c#genericsinheritanceentitymediatr

Inherit from a generic base class in C#


I want to inherit from a generic TEntity but I get this error:

Compiler Error CS0689
Cannot derive from 'identifier' because it is a type parameter

Base classes or interfaces for generic classes cannot be specified by a type parameter. Derive from a specific class or interface, or a specific generic class instead, or include the unknown type as a member.

This is my code:

public class CreateCategoryCommand<TEntity> : TEntity, IRequest<CategoryDtoSelect>
{
}

Solution

  • That's just not possible.

    You cannot inherit from the the type used as a type argument. The reason is that the compiler would need to know the methods and fields of TEntity to create the derived class. But since it's generic, that doesn't work.

    You can either inherit from another class taking TEntity as type parameter or go with aggregation instead. You can declare a field of type TEntity.