Search code examples
c#genericsinner-classestype-parameter

Using a class nested in a generic class as type parameter in C#


Having the following definition:

public class Generic<T>
{
    public class Nested { }
}

And given that ECMA ref §25.1 states:

Any class nested inside a generic class declaration or a generic struct declaration (§25.2) is itself a generic class declaration, since type parameters for the containing type shall be supplied to create a constructed type.

I understand that Nested requires the type parameter in order to be instantiated.

I can obtain the generic Type with typeof:

var type = typeof(Generic<>.Nested); 
// type.FullName: Namespace.Generic`1+Nested

Is there any way I can use it as a type parameter for a generic method such as the following?

var tmp = Enumerable.Empty<Generic<>.Nested>(); 
// Error: Unexpected use of an unbound generic

As stated before, from the ECMA specification I understand that all the type parameters must be satisfied before instancing but no objects are being created here. Furthermore, the Nested class does not make use of the type parameters in any way: I simply would like to define it nested for code organization purposes.


Solution

  • No, you can't do that. As you said

    all the type parameters must be satisfied before instancing

    and though no instance of Generic<>.Nested is actually generated

    • the compiler does not know the semantics of Empty (so doesn't know that no instance of Generic<>.Nested is created)
    • and the main problem: you do want to create an instance of IEnumerabe<Generic<>.Nested>, which would be a type with "unsatisfied type parameters", too