I am trying to get a copy of the type and its heirs.

assembly.GetTypes() .Where(t => !t.IsAbstract && (t.IsSubclassOf(typeof(T)) || t.IsEquivalentTo(typeof(T)))) .Select(Activator.CreateInstance) .OfType<T>() 

Is there really no easier way? IsSubclassOf skips the type itself, and IsAssignableFrom for some reason does not return heirs, although I may have misunderstood what it does.

  • IsAssignableFrom - checks that a variable of one type to be checked can be assigned a value of the parameter type - Grundy
  • Are you generic types trying to find? - sp7
  • @ sp7, no, just a generic method, for ease of use. And I try to create an instance of the passed type and its heirs. - Monk
  • @Grundy works the other way around, checking the heir makes sure that the generic type cannot be assigned? Then I understand why it does not suit me. - Monk
  • @Monk, why not fit? :-) if you swap the parameters, everything starts coming up :) - Grundy

1 answer 1

As suggested in the comments, Type.IsAssignableFrom helps determine if an instance of the specified type can be assigned to an instance of the current type. Thus, if you call it from the base type:

 typeof(T).IsAssignableFrom(t) 

That turns out both the type and its successors. So, the search looks a bit simpler and clearer:

 assembly.GetTypes() .Where(t => !t.IsAbstract && t.IsClass && typeof(T).IsAssignableFrom(t)) .Select(Activator.CreateInstance) .OfType<T>()