C # generation methods and returning an object of a parameterized type created in a method from xml

I have a method in which I would like to return an instance of an object of a parameterized type T ie. Foo<T> .

Type T is created within the method using GetType() from a string element in an XML file. Since neither the class nor the method knows about it before it was created, I also cannot parameterize it.

Is there a way to return an object of type Foo<T> from a non-generic method?

EDIT: this is the signature of a method, for example:

  public Foo<T> getFooFromXml(string name) { 

where is the type created internally and the method and class are nonequivalent?

+4
source share
2 answers

In response to your edit:

This method signature is not valid anyway. You must know T at compile time to return Foo from the method. Consider my suggestion in the comments on my last answer, where you will have a separate IFoo interface that implements Foo.

 class Foo<T> : IFoo { public T DoSomething() { ... } object IFoo.DoSomething() { return DoSomething(); } } interface IFoo { object DoSomething(); } 
+1
source

Yes, basically you need to get an 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: Notice that I used typeof (Foo <>) above, I intentionally left the angle brackets empty.

+8
source

All Articles