jessehouwing
jessehouwing

Reputation: 114721

Get the container type for a nested type using reflection

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.

Upvotes: 33

Views: 7132

Answers (3)

PMF
PMF

Reputation: 17248

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.

Upvotes: 0

ikh
ikh

Reputation: 2436

Sounds like you're looking for Type.DeclaringType property.

Upvotes: 5

Martin1921
Martin1921

Reputation: 653

You can get this by retrieving the property "DeclaringType".

Quoting MSDN:

A Type object representing the enclosing type, if the current type is a nested type; or the generic type definition, if the current type is a type parameter of a generic type; or the type that declares the generic method, if the current type is a type parameter of a generic method; otherwise, null.

http://msdn.microsoft.com/en-us/library/system.type.declaringtype.aspx

Upvotes: 42

Related Questions