Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generics methods and returning a object of a parameterized type created in the method from xml

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?

like image 294
theringostarrs Avatar asked Jan 23 '23 14:01

theringostarrs


1 Answers

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.

like image 190
Josh Avatar answered Jan 26 '23 03:01

Josh