Having T type how to find all classes that expand Base<T> in assembly?

Say I have:

public class Base<T> {}
public class MyBaseOne : Base<int> {}
public class MyBaseTwo : Base<int> {}

Having T type (say int) how to find all classes that expand Base in the assembly and be able to construct new objects of them?

Jon Skeet
people
quotationmark

You can use Type.IsAssignableFrom:

var typeArgument = typeof(int);
var baseType = typeof(Base<>).MakeGenericType(typeArgument);
var matches = someAssembly.GetTypes()
                          .Where(t => typeof(baseType).IsAssignableFrom(t));

That will work for the examples you've shown, but won't find (say) Child<T> where Child is described as:

public class Child<T> : Base<T>

I'm assuming you do want to find classes that are assignable to Base<T> but don't have Base<T> as the direct superclass (i.e. a longer type hierarchy). If you don't, it's even easier:

var matches = someAssembly.GetTypes().Where(t => t.BaseType == baseType);

people

See more on this question at Stackoverflow