Reputation: 12390
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?
Upvotes: 4
Views: 10254
Reputation: 69262
In response to your edit:
That method signature isn't valid anyway. You need to know T at compile time in order to return Foo from a method. Consider my suggestion in the comments on my last answer where you would have a separate interface IFoo that Foo implements.
class Foo<T> : IFoo {
public T DoSomething() {
...
}
object IFoo.DoSomething() {
return DoSomething();
}
}
interface IFoo {
object DoSomething();
}
Upvotes: 1
Reputation: 69262
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.
Upvotes: 8