Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot inherit with generics

Tags:

c#

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?

like image 664
jokulmorder Avatar asked Oct 01 '22 21:10

jokulmorder


1 Answers

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.

like image 189
Ondrej Tucny Avatar answered Oct 10 '22 23:10

Ondrej Tucny