I need to use a generic interface like the following:
public interface IContainer<T>
{
IEnumerable<IContent<T>> Contents { get; }
}
An object implementing this interface is returned by a generic method like the following:
IContainer<T> GetContainer<T>(IProperty property);
Type T is unknown until run-time.
Using reflection I am able to invoke the GetContainer<T> method and get the result.
My problem is that I don’t know how to enumerate the result which has type Object (therefore I cannot cast it to IEnumerable).
I have also tried casting as follows but it does not work (it says “Type is expected”):
var myContainer = genericMethodInfo.Invoke(
myService,
new object[] { property })
as typeof(IContainer<>).MakeGenericType(type);
where type is the runtime type, myService is the service exposing the GetContainer<T> method, and property is of type IProperty as needed.
UPDATE: see my complete solution in my blog: http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/
typeof(IContainer<>).MakeGenericType(type) will only evaluate at runtime, while “as” needs to know the type at compiler time.
What I really don’t understand is this comment: My problem is that I don’t know how to enumerate the result which has type Object (therefore I cannot cast it to IEnumerable).
myContainer may be an Object but it can surely be cast to IEnumerable? If it can’t then it can’t be enumerated.