Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: Why is nested class having generics declaring in outer class?

Tags:

c#

.net

cil

Because the Type.FullName is a bit ugly, I need to make my beautiful name constructor. But when I used Type.GetGenericArguments() I ran into one problem.

Generic T of outer class C1 is always distributed to nested classes C2 and C3.

class C1<T> {
    public class C2<T1, T2> {
    }
    public class C3 {
    }
}

typeof( C1<> ).ToString(); // C1`1[T]
typeof( C1<>.C2<,> ).ToString(); // C1`1+C2`2[T,T1,T2]
typeof( C1<>.C3 ).ToString(); // C1`1+C3[T]

Two questions:

  • How to determine whether generic type came from outer class or not?
  • What is the reason for this behavior?
like image 418
Denis535 Avatar asked Nov 28 '25 03:11

Denis535


1 Answers

Type parameters are not "inherited" by nested classes in CIL. There, your class looks like this:

.class private auto ansi beforefieldinit C1`1<T> extends [mscorlib]System.Object
{
    .class nested public auto ansi beforefieldinit C2`2<T, T1, T2> extends [mscorlib]System.Object
    {
    }

    .class nested public auto ansi beforefieldinit C3<T> extends [mscorlib]System.Object
    {
    }
}

Since the definition of a nested type does not actually depend on the parent type, the outer generic arguments need not be accessible to it, and so it was decided they must be repeated explicitly, like C# does, but there is support for languages that work in a different fashion (where C1<>.C3 could be a concrete type).

Your question is then one of obtaining a C# type expression from a .NET type. You may have luck with CodeDOM, or simply assume that if the generic parameters of the nested type have the same name as those of the parent type, you can omit them when creating the string.

So, to reiterate, generic parameters cannot come from the outer class in .NET, that is merely C#'s behaviour. If you assume the class was created in C#, you can simply remove the parameters based on their names.

like image 127
IS4 Avatar answered Nov 29 '25 18:11

IS4



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!