giotto
giotto

Reputation: 39

Generic class with generic type parameter stored in string

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

Answers (1)

Felipe Oriani
Felipe Oriani

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

Related Questions