Question

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!

Was it helpful?

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.

OTHER TIPS

The method Type.GetType(someString) gets the type at runtime, but generics class must be evaluated at compiled time. Between the <> symbols you need to specify the type itself and not an instance of the object Type. Something like this must work:

MyClass<String> obj = new MyClass<String>();

Thanks,

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top