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/
Sorry if I misunderstood, I was having trouble understanding exactly what your objective was. Were you looking for something like this?
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.
If you're thinking of moving to .Net 4 that is what the dynamic type provides.
I'm assuming that your object will only be returned as being one of a restricted number of types, so why not test against those before casting e.g. if object is thisclass?
First, when casting you need a type (double, int); typeof takes a type argument and returns a class of type Type.
Second, here is some example code:
Your type T must be known by the compiler, so this will not work. You can try making a non generic version of your interface, like this:
This way you have something to cast to and are able to use it.