O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required