Search code examples
c#umlclass-diagramclass-referenceclass-relationship

Determine Class Associations using Reflection


I am working on a solution that extracts all the class associations between each other. If we click a class in the object browser we can see the option Find All References. I want something similar that finds the associations a class has to other classes. How can we find them using Reflection?

I am interested in Extracting

  1. Composition Relationship:
  2. Aggregation Relationship
  3. Association Relationship
  4. Inheritance

Solution

  • You can use Reflection in order to list all properties, fields and methods (and more) of a class. You would have to inspect these and determine their types and parameter lists. Probably it would be a good idea to discard types from the System namespace.

    Type t = typeof(MyClass);
    
    // Determine from which type a class inherits
    Type baseType = t.BaseType;
    
    // Determine which interfaces a class implements
    Type[] interfaces = t.GetInterfaces();
    
    // Get fields, properties and methods
    const BindingFlags bindingFlags =
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
    FieldInfo[] fields = t.GetFields(bindingFlags);
    PropertyInfo[] properties = t.GetProperties(bindingFlags);
    MethodInfo[] methods = t.GetMethods(bindingFlags);
    
    foreach (var method in methods) {
        // Get method parameters
        ParameterInfo[] parameters = method.GetParameters();
    }
    

    Intellisense will tell you (almost) all the secrets of FieldInfo, PropertyInfo, MethodInfo and ParameterInfo. You might also consider examining the generic parameters of the class, events and more.