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.

Answers


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


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


Need Your Help

How is C# inspired by C++ more than by Java?

c# java c++ programming-languages language-history

When looking at the history of C#, I found out that C# was seen as an update to C and/or C++. This came a bit as a surprise to me, as on the surface, I see much more common ideas between C# and Java (

printing "<html>" using html

html escaping symbols html-entities

How do I print the "html" tag, including '&lt;' and '>'? How can I do this for any tag, without using text areas and Javascript?