OT: Help discovering actual type of generic parameter from nested type?

OT: Help discovering actual type of generic parameter from nested type?

Old forum URL: forums.lhotka.net/forums/t/5801.aspx


rsbaker0 posted on Thursday, November 13, 2008

I've having trouble discovering the actual type of a generic parameter from an instance (or the type of an instance) of a nested class. Here is short example:

    class G<T>
    {
        public class NestedC { }
        public enum NestedEnum { A, B }
    }

    class Derived : G<Derived>
    {

        public static void Test()
        {
            NestedC X = new NestedC();
            Type c = X.GetType();
            System.Diagnostics.Debug.WriteLine("Type is " + c.FullName);
        }

Calling Derived.Test() produces this output:

Type is G`1+NestedC[[Derived, TestAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]

Clearly, the actual type of T is known since it shows up in the name here. However, I really can't see how to get the type "Derived" programmatically. If I using DeclaringType, then I get:

FullName = "G`1"

And then trying to get the generic arguments gives me "T", not the actual type.

Can anyone help me resolving the actual type here?

FatPigeon replied on Friday, November 14, 2008

How about:

           System.Diagnostics.Debug.WriteLine("Result: " + c.GetGenericArguments()[0].Name);

Regards,

 

Patrick

rsbaker0 replied on Friday, November 14, 2008

That works. Thanks!

(I saw that method, but was confused because ContainsGenericParameters was false. Evidently that is used for something else)

Copyright (c) Marimer LLC