Suppose I have an interface: IFoo<T1,T2> and a class Moo<T1> : IFoo<List<T1>, Stack<T1>>.
At runtime I can call: typeof(Moo<>).GetInterfaces() and it gives me an array with one type in it, so I guess that in some sense the type typeof(IFoo<List<>, Stack<>>) can be created at runtime. However, that syntax does not work.
What is the correct syntax to define that type at runtime?
Though that statement is true, your logic is not sound because the true conclusion does not follow logically from the premise you’ve stated. The type returned by
is not
IFoo<T1, T2>constructed withList<>andStack<>in the first place.Rather, it is
IFoo<T1, T2>constructed withList<T1>andStack<T1>, whereT1is theT1ofMoo<T1>, not theT1ofIFoo<T1, T2>. When making sample code to discuss type construction, I strongly discourage you from making type parameters that are logically different but have the same name. It is very confusing.In case that is not clear, let’s take a step back. Every generic type has an associated type called its instance type, which is the generic type constructed with its own type parameters. That is, when you say:
From the compiler’s perspective, the types
C<>andC<T>are the same type. But these will be different type objects at runtime because of course at runtime there will never be an instance ofC<T>, onlyC<int>orC<string>or whatever. The firsttypeofsyntax gives you the type as it is constructed at runtime. The second gives you the instance type from the perspective of the compiler.So let’s consider your case in more detail. Suppose you have:
then
typeof(E<>).GetInterfaces()[0]is the type as it is known to the compiler, namely,I<C<X>, D<X>>. ButI<C<>, D<>>is a completely different type; that isI<C<V>, D<W>>which is not at all the same type from the compiler’s perspective.There is none.
There is no C#
typeofsyntax that produces the type “generic type constructed with type arguments that are the instance types of other generic types”. That would be:To give you
I<C<V>, D<W>>.Nor is there a
typeofsyntax for “generic type constructed with the type parameters of a different generic type”. kvb’s answer gives the Reflection code needed to buildI<C<X>, D<X>>.I am curious as to why you would want to construct such a bizarre type in the first place. What’s your application?