Reputation: 39
Is there a way in C# to get the definition of a type from a string? I'd like to use it as a generic type parameter.
This is what i'd like to achieve in the end.
string classname = "Class1"; GenericClass<Class1> gc = new GenericClass<Class1>(); gc.Method();
is there any possible way?
Upvotes: 0
Views: 56
Reputation: 38626
Yes, you can use reflection to do it and sometimes it cannot be too safe, try something like this article sample.
Type d1 = typeof(GenericClass<>);
Type[] typeArgs = { Type.GetType("Class1") };
Type makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
But you will not get all intellisense from visual studio.
Upvotes: 3