Implementations of interface through Reflection

The answer is this; it searches through the entire application domain — that is, every assembly currently loaded by your application.

/// <summary>
/// Returns all types in the current AppDomain implementing the interface or inheriting the type. 
/// </summary>
public static IEnumerable<Type> TypesImplementingInterface(Type desiredType)
{
    return AppDomain
           .CurrentDomain
           .GetAssemblies()
           .SelectMany(assembly => assembly.GetTypes())
           .Where(type => desiredType.IsAssignableFrom(type));
}

It is used like this;

var disposableTypes =  TypesImplementingInterface(typeof(IDisposable));

You may also want this function to find actual concrete types — i.e., filtering out abstracts, interfaces, and generic type definitions.

public static bool IsRealClass(Type testType)
{
    return testType.IsAbstract == false
         && testType.IsGenericTypeDefinition == false
         && testType.IsInterface == false;
}

Leave a Comment

tech