Retrieve nested private types in C# using reflection

Retrieve nested private types in C# using reflection
typescript
Ethan Jackson

It is possible to retrieve all the nested types of a class in C# using reflection using Type.GetNestedTypes. However, those nested types are restrained to public types only.

In the following scenario, how to enumerate all the nested types, regardless of their visibility?

public sealed class Foo { public Foo() { foreach(var type in GetType().GetNestedTypes()) { /** Only NestedPublic will be enumerated */ } } public class NestedPublic { } private class NestedPrivate { } }

Answer

You need to use the overload accepting BindingFlags:

GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic)

Related Articles