Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 292
Paul Avatar asked Mar 26 '09 20:03

Paul


People also ask

How do you declare a generic class?

A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.

What is generic in C# with example?

Generic Class T is called type parameter, which can be used as a type of fields, properties, method parameters, return types, and delegates in the DataStore class. For example, Data is generic property because we have used a type parameter T as its type instead of the specific data type.


3 Answers

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" });
like image 135
alex Avatar answered Oct 14 '22 10:10

alex


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

like image 34
Frans Bouma Avatar answered Oct 14 '22 10:10

Frans Bouma


This is a job for the dynamic keyword coming in C# 4.0.

There are some nice hacks here that will get you an instance of your object, but no matter what the current version of C# will only know it has an object, and it can't do much with an object by itself because current C# does not support late binding. You need to be able to at least cast it to a known type to do anything with it. Ultimately, you must know the type you need at compile time or you're out of luck.

Now, if you can constrain your repository class to types implementing some known interface, you're in a much better shape.

like image 35
Joel Coehoorn Avatar answered Oct 14 '22 09:10

Joel Coehoorn