This is what I use to find all children of some class (can be also abstract class) in selected assembly:
public class InheritedFinder
{
public static Type[] FindInheritedTypes(
Type parentType, Assembly assembly)
{
Type[] allTypes = assembly.GetTypes();
ArrayList avTypesAL = new ArrayList();
return allTypes.Where(
t => parentType.IsAssignableFrom(t) && t != parentType).ToArray();
}
}
Simply call by
var availableTypes = InheritedFinder.FindInheritedTypes(
typeof(YourBaseClass),
System.Reflection.Assembly.GetExecutingAssembly());
This will give you list of available children of YourBaseClass. Nice thing about it - it'll find also children of children, so you can use multi-level abstract classes. If you need to create instances of every child, easy:
var availableTypes= InheritedFinder.FindInheritedTypes(
typeof(Shape), System.Reflection.Assembly.GetExecutingAssembly());
foreach (var t in availableTypes)
{
try
{
YourBaseClass nInstance = (YourBaseClass)Activator.CreateInstance(t);
//nInstance is now real instance of some children
}
catch (Exception e)
{
//recommended to keep here - it'll catch exception in case some class is abstract (=can't create its instance)
}
}
t.IsAssignableFrom(pType)
will return false. – Siebert