DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 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 processing on this type needs to be done. Interfaces are also discarded since they cannot contain nested types.

Usually the dot operator is used to delimit namespaces and types; however, nested types are somewhat special. Nested types are set apart from other types by the + operator in their fully qualified name when dealing with them in the Reflection API. By passing this fully qualified name in to the static GetType methods, the actual type that it represents can be acquired.

These methods return a Type object that represents the type identified by the typeName parameter.

Calling Type.GetType on a type in a dynamic assembly (one that is created using the types defined in the System.Reflection.Emit namespace) returns a null if that assembly has not already been persisted to disk.


See Also

See Recipe 12.11; see the "Assembly Class" and "BindingFlags Enumeration" topics in the MSDN documentation.

    [ Team LiB ] Previous Section Next Section