Reflecting Over a Type Hierarchy

Once you have retrieved a Type instance, you can navigate the application hierarchy described earlier, accessing the metadata via types that represent members, modules, assemblies, namespaces, AppDomains, and nested types. You can also inspect the metadata and any custom attributes, create new instances of the types, and invoke members.

Here is an example that uses reflection to display the members in three different types:

using System;
using System.Reflection;
class Test {
  static void Main( ) {
    object o = new Object( );
    DumpTypeInfo(o.GetType( ));
    DumpTypeInfo(typeof(int));
    DumpTypeInfo(Type.GetType("System.String"));
  }
  static void DumpTypeInfo(Type t) {
    Console.WriteLine("Type: {0}", t);
  
    // Retrieve the list of members in the type
    MemberInfo[ ] miarr = t.GetMembers( );
  
    // Print out details on each of them
    foreach (MemberInfo mi in miarr)
      Console.WriteLine("  {0}={1}", mi.MemberType, mi);
  }
}

Get C# in a Nutshell, Second Edition 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.