35

As per the title. I'd like a list of all the inner classes of a given class, it can be a list of names or a list of types - I am not fussed. Is this possible? I thought there might be a way using reflection but haven't been able to find one.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Dr. Thomas C. King
  • 993
  • 2
  • 15
  • 28
  • 4
    Also, use of the phrase "inner classes" suggests you may have Java experience. It is worth pointing out that in C# these are called "nested classes", and they are closer to Java's "static nested classes" than Java's "inner classes". – Kevin Cathcart Apr 06 '11 at 14:10

5 Answers5

53

You want Type.GetNestedTypes. This will give you the list of types, which you can then query for their names.

Chris Pitman
  • 12,990
  • 3
  • 41
  • 56
12

Doesn't Type.GetNestedTypes do what you want?

Note that if you want to get "double-nested" types, you'll need to recurse - as Foo.Bar.Baz is a nested type in Foo.Bar, not in Foo.

For "modern" environments (.NET 4.5, PCLs, UWA etc) you need TypeInfo.DeclaredNestedTypes instead, e.g. type.GetTypeInfo().DeclaredNestedTypes, using the GetTypeInfo() extension method.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
7

Type.GetNestedTypes() will return the public nested types of the specified Type.

If you also want the private and internal nested types, you must call the Type.GetNestedTypes(BindingFlags bindingFlags) method like this:

Type[] nestedTypes = typeof(MyType).GetNestedTypes(BindingFlags.Static |
                                                   BindingFlags.Instance |
                                                   BindingFlags.Public |
                                                   BindingFlags.NonPublic);
Jeff Cyr
  • 4,774
  • 1
  • 28
  • 42
4
Type[] nested = typeof(SomeClass).GetNestedTypes();
Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
3

Yes, there is. Use Type.GetNestedTypes().

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443