1

What I am trying to do is create a dynamic way to unlock Records in that database after the time is up. A string is passed that is the types name.

I pass a string of the type to a JsonResult, this string contains the name of the class that I would like to create a Type from. I then want to create a GenericRepository from the Type that I just created.

I keep getting the error 'type1' is a variable but is used like a type. Is this a possible scenario?

public JsonResult UnlockRecord(string modelType)
    {


        Type type1 = Type.GetType(modelType);

        GenericRepository<type1> typeRepository = new GenericRepository<type1>();
        type1 lockedRecord = typeRepository.GetFirst();
        typeRepository.BatchUnlock(type1.Id);

        return Json(null);
    }
Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
Eric
  • 212
  • 2
  • 15
  • Possible duplicate of [Pass An Instantiated System.Type as a Type Parameter for a Generic Class](https://stackoverflow.com/questions/266115/pass-an-instantiated-system-type-as-a-type-parameter-for-a-generic-class) – JohnLBevan Oct 25 '18 at 15:48

1 Answers1

2

I think you're looking to create a generic type. You'd do this through reflection using MakeGenericType and Activator.CreateInstance

var repoType = typeof(GenericRepository<>).MakeGenericType(Type.GetType(typeName));
var repo = Activator.CreateInstance(repoType);

If your repository has constructor arguments you'll need to pass those as well.

JSteward
  • 6,833
  • 2
  • 21
  • 30