Retrieve nested private types in C# using reflection

Retrieve nested private types in C# using reflection

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)

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles