1

In C# it is easy to create an open generic type, typeof(IEnumerable<>). Is there a way to create a type that contains an open generic? The following does not work: typeof(IEnumerable<IFoo<>>).

myermian
  • 31,823
  • 24
  • 123
  • 215

2 Answers2

4

Get the two unbound generic types involved, and then use one as the argument to making a generic type from the other:

typeof(IEnumerable<>).MakeGenericType(typeof(IFoo<>))
Jon Hanna
  • 110,372
  • 10
  • 146
  • 251
  • And this doesn't causes an exception? according to the MSDN docs an unbound type can just be used on the typeof sentences, and using it with MakeGenericType would not be allowed... – Gusman Oct 20 '16 at 03:18
  • @Gusman perhaps the doc you are thinking about refers to the C# syntax for referring to types, rather than the `Type` objects themselves? "typeof sentences" presumably refers to the C# syntax using `typeof`. The objects returned by such expressions are still `Type` objects and the main reason for having such sentences in the first place is to then produce the related bound type. In the case here we have a bound type that is bound to an unbound type, but in C# we still needed `typeof` giving us the unbound to get us that far... – Jon Hanna Oct 20 '16 at 09:45
  • ... Compare with how we can't do `typeof` to get `ref` (including `out`) types directly, but can do `typeof(int).MakeByRefType()` to get one. – Jon Hanna Oct 20 '16 at 09:46
  • @Gusman are you thinking of where in the C# spec it says "An unbound generic type can only be used within a typeof-expression"? That is indeed exactly what I did here, but then having obtained two objects from two typeof expressions, I worked with the result of those expressions. – Jon Hanna Oct 20 '16 at 09:48
1

There's no way. These aren't generic but unbound types, these are special types, they can't be instantiated. An unbound generic type can only be used within a direct typeof-expression.

When you use typeof(IEnumerable<IFoo<>>) you aren't using the unbound type in the typeof expression but in the IEnumerable<T> expression.

Gusman
  • 14,905
  • 2
  • 34
  • 50