Home > OS >  how to pass classtype dymanically to generic class
how to pass classtype dymanically to generic class

Time:10-10

i have this kind of requirement as there are around 100 models

I have repository pattern implemented for DB operations

public class interface IRepository<TEntity> : IRepository<TEntity>where TEntity : class

it has method Task Add(TEntity entity);

in normal circumstances ,i would just do this if i want to add UserClass model to DB

public class UserClass {string Name}
    
UserClass userClassObj = new UserClass {Name = "John"}

await Repository <UserClass>.Add(userClassObj);

However, my requirement is to pass pass class type dynamically based on condition as i have around 100 models.

if (condition == "1")
   classtype = USerClass
else if (condition == "2")
   classtype = DepartmentClass
else if (condition == "3")
   classtype = CategoryClass

and then pass classtype to Repository await Repository <classtype>.Add(object of (classtype ));

is this doable? any working example will be highly apricated. could not found straight forward implementation so far.

CodePudding user response:

You might need to extend your class definition like this,

public class interface IRepository<TEntity> : IRepository<TEntity>where TEntity : class, new()

new() enables creating new object based on passed type.

then you can call it like this,

if (condition == "1")
   await Repository<USerClass>.Add(object);
else if (condition == "2")
   await Repository<DepartmentClass>.Add(object);

CodePudding user response:

If you don't want to use Reflection may add an extra add helper method to (maybe also to your IRepositoryType not sure if this<T> work)

 public static async Task Add<T>(T objectToAdd) where T : TEntity
 {
    await Repository<T>.Add(objectToAdd)
 }

if you have the type argument and a parameter that needs the type you dont have to specify it any more and it will chosoe usually the right type argument with the given parameter type. E.g.

var userObject = new UserObject();
Repository.Add(userObject);

will automaticly detect that it is the userbject the type to be add

another possibility would be to use a Dictionary<Type,yourDBsetType>() and match it by the type key

  • Related