jokul
jokul

Reputation: 1339

Cannot inherit with generics

This class declaration:

public abstract class Repository<TE, TD>
    where TE : class, IEntity, new()
    where TD : DataProvider<TE>

Cannot be fulfilled by this class signature:

public class SqlRepository<TE> : Repository<TE, SqlDataProvider>
    where TE : SqlEntity, new()

Where SqlEntity : IEntity and SqlDataProvider : DataProvider<SqlEntity>, I get this error:

Error 1 The type ~ cannot be used as type parameter 'TD' in the generic type or method '~.Repository'. There is no implicit reference conversion from '~.SqlDataProvider' to '~.DataProvider'.

Why can it not convert the SqlEntity to the interface it implements?

Upvotes: 5

Views: 92

Answers (1)

Ondrej Tucny
Ondrej Tucny

Reputation: 27962

The problem is what in SqlRepository<TE> you are fixing TD's inner generic parameter, which is linked to TE in Repository<TE, TD> declaration, to be SqlEntity but this cannot be told about TE, which is left generic.

What you can do, is keep TD generic in SqlDataProvider like this:

public class SqlDataProvider<TD> : DataProvider<TD> 
    where TD : SqlEntity

and then surface this dependency in SqlRepository like this:

public class SqlRepository<TE> : Repository<TE, SqlDataProvider<TE>>
    where TE : SqlEntity, new()

This compiles, because TE usage is consistent.

Upvotes: 4

Related Questions