Search code examples
c#reflectionactivator

Create an instance of a custom generic class and a type stored in file as String


I am trying to create an instance of a generic class but my Type T of the generic class, i have gone through this link http://msdn.microsoft.com/en-us/library/w3f99sx1(v=vs.110).aspx but i couldn't find what i was looking for

i have this code

public class MyClass<T>
{
    public T prop { get; set; } 
}

and i have the type stored in string the type

string typeString = "System.String";

now i want to use this type in myclass this way

Type xt = new Type.GetType(typeString);
MyClass<xt> obj = new MyClass<xt>();

but that just unidentified type xt so what do i do!


Solution

  • The section Constructing an Instance of a Generic Type in the link provided covers this exact case.

    In your case you would need write

    Type typeArgument = Type.GetType(typestring);
    Type constructed = typeof(MyClass<>).MakeGenericType(typeArgument);
    object instance = Activator.CreateInstance(constructed);
    

    However, the use cases of this techniques are far from common. You should try as much as possible to provide type information at compile-time. That is, try not to rely on Reflection to create your objects. Generics methods are especially useful for such cases.