Get instances of each implementation of a given type

I needed this method, I needed it before and will probably need it again.
Creating an enum of instances of a given type as a generic method. Requires the types to have a parameterless constructor.

public IEnumerable GetInstances()
    var baseType = typeof(T);
    var types = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(s => s.GetTypes())
        .Where(type => !type.IsAbstract && baseType.IsAssignableFrom(type))
        .Select(x => (T) Activator.CreateInstance(x));
    return types;

No comments:

Post a Comment