I have a method where I would like to return an object instance of parameterized type T ie. Foo<T>
.
The type T is instantiated within the method using GetType()
, from a string element in an XML file. Since neither the class or method knows about it before it is created, I cant parameterize either.
Is there a way I can return an object of type Foo<T>
from the non-generic method?
EDIT: That is a method signature such as:
public Foo<T> getFooFromXml(string name) {
where the type is created inside, and the method and class are both non-generic?
Yeah, basically you have to get the open generic type and create a closed generic type.
Type openType = typeof(Foo<>);
Type closedType = openType.MakeGenericType(typeof(string));
return Activator.CreateInstance(closedType); // returns a new Foo<string>
EDIT: Note that I used typeof(Foo<>) above, I intentionally left the angle brackets empty.
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