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!
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With