13.5. Determining and Obtaining Nested Types Within an Assembly
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)
{
var names = from t in Assembly.LoadFrom(asmPath).GetTypes()
from t2 in t.GetNestedTypes(BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic)
where !t2.IsEnum && !t2.IsInterface
select t2.FullName;
foreach (string name in names)
{
Console.WriteLine(name);
}
}Discussion
The DisplayNestedTypes method uses a LINQ query to query all types in the assembly specified by the asmPath parameter. The LINQ query also queries for the nested types with the assembly by using the GetNestedTypes method of the Type class.
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 APIs. By passing this fully qualified name in to the static GetType methods, the actual type ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access