12.6. Obtaining Types Nested Within a Type

Problem

You need to determine which types have nested types contained within them in your assembly. Determining the nested types allows you to programmatically examine various aspects of some design patterns. Various design patterns may specify that a type will contain another type; for example, the Decorator and State design patterns make use of object containment.

Solution

Use the DisplayNestedTypes method to iterate through all types in your assembly and list all of their nested types. Its code is:

public static void DisplayNestedTypes(string asmPath)
{
    bool output = false;
    string line;
    Assembly asm = Assembly.LoadFrom(asmPath);
    foreach(Type asmType in asm.GetTypes( ))
    {
        if (!asmType.IsEnum && !asmType.IsInterface)
        {
            line = asmType.FullName + " Contains:\n" ;
            output = false;

            // Get all nested types
            Type[] nestedTypes = asmType.GetNestedTypes(BindingFlags.Instance |
                BindingFlags.Static |
                BindingFlags.Public |
                BindingFlags.NonPublic);

            // roll over the nested types
            foreach (Type t in nestedTypes)
            {
                line += "   " + t.FullName + "\n";
                output = true;
            }
            if (output)
                Console.WriteLine(line);
        }
    }
}

Discussion

The DisplayNestedTypes method uses a foreach loop to iterate over all nested types in the assembly specified by the asmPath parameter. Within this foreach loop, any enumeration and interface types are discarded by testing the IsEnum and IsInterface properties of the System.Type class. Enumeration types will not contain any types, and no further ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.