How do I create a generic class from a string in C#? [duplicate]

I have a Generic class like that :

public class Repository<T> {...}

And I need to instance that with a string ... Example :

string _sample = "TypeRepository";
var _rep = new Repository<sample>();

How can I do that? Is that even possible?

Thanks!


Here is my 2 cents:

Type genericType = typeof(Repository<>);
Type[] typeArgs = { Type.GetType("TypeRepository") };
Type repositoryType = genericType.MakeGenericType(typeArgs);

object repository = Activator.CreateInstance(repositoryType);

Answering the question in comment.

MethodInfo genericMethod = repositoryType.GetMethod("GetMeSomething");
MethidInfo closedMethod = genericMethod.MakeGenericMethod(typeof(Something));
closedMethod.Invoke(repository, new[] { "Query String" });

First get the Type object using Type.GetType(stringContainingTheGenericTypeArgument)

Then use typeof(Repository<>).MakeGenericType(theTypeObject) to get a generic type.

And finally use Activator.CreateInstance