Get the container type for a nested type using reflection

Viewed 6287

Say I have a class like this:

public class Test {
    public class InnerTest{}
}

Now have a TypeInfo object for InnerTest. How can I find out the TypeInfo object for Test from InnerTest?

The other way around is simple, I can just use GetNestedTypes(), but I can't find a method or property (other than IsNestedType) to figure out the containing class for a Nested Class.

3 Answers

In addition to the above, I want to add that it gets a bit complicated if generic types are involved, because the generic type arguments are defined on the Type of the inner instance not the DeclaringType.

Consider this class:

internal class WithGenericArg<T>
    {
        private T _data;

        public WithGenericArg(T data)
        {
            _data = data;
        }

        public class Internal
        {
            public int Foo()
            {
                return 0;
            }
        }

        public class Internal2<T2>
        {
            public T2? _data2;

            public Internal2(T2? data2)
            {
                _data2 = data2;
            }

            public T2? Foo2()
            {
                return _data2;
            }
        }
    }

When looking at the type of Inner its IsGenericType property is true and GetGenericArguments() returns 1 element (as well as GenericTypeArguments returns 1 element when the type is closed). This is the type argument (or concrete type) for the type argument of the outer(!) class.

When looking at the type of Inner2 there are even 2 type arguments, one for the outer class and one for the inner.

Related