Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with generic to apply constraints

Tags:

c#

generics

I have these models class:

public abstract class ModelBase<T>
{
   public virtual T Id { get; set; }
}

public class Table: ModelBase<int>
{
   public string Name { get; set; }
}

My problem is when I need to work with my repository and I need the type is Table and put the type parameters or constraints:

public class Repository<TEntity> 
         : IRepository<TEntity> where TEntity 
         : ModelBase<T> //I know there's a mistake, but as it is needed

How I can do that infers the type that is in Table in this case is int or a reference to it?

TEntity in this case is Table

like image 722
andres descalzo Avatar asked Dec 22 '25 04:12

andres descalzo


1 Answers

You were pretty close. In order to use T in your example, you need to provide that type. In order to provide the type, it needs to be passed to the class constructor so it needs to be in the definition. You can include it as like this

public class Repository<TEntity,T> 
                              //^ Include the type in the definition
     : IRepository<TEntity> where TEntity 
     : ModelBase<T>

and now when you instantiate you need to pass both the table, and the table's type

var repo = new Repository<Table,int>();
like image 158
Travis J Avatar answered Dec 23 '25 17:12

Travis J