Skip to content

Instantly share code, notes, and snippets.

@wolf99
Created March 31, 2017 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolf99/b28286c6887a13993d60c2fcf32012b2 to your computer and use it in GitHub Desktop.
Save wolf99/b28286c6887a13993d60c2fcf32012b2 to your computer and use it in GitHub Desktop.
Class that lists all the types derived from a given type. Taken from http://stackoverflow.com/a/6944605/1292918
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace FooProgram
{
public static class DerivedClassEnumerator
{
// Class that list all the types derived from a given type
// Taken from http://stackoverflow.com/a/6944605/1292918
// - Uses Assembly.GetAssembly(typeof(T)) because the base class might be in a different assembly.
// - Use the criteria type.IsClass and !type.IsAbstract because it'll otherwise throw an exception
// if it tries to instantiate an interface or abstract class.
// - Child classes must have identical constructor signatures, otherwise it'll throw an exception.
static DerivedClassEnumerator() { }
public static IEnumerable<T> GetObjectsDerivedFromType<T>(params object[] constructorArgs) where T : class//, IComparable<T>
{
List<T> objects = new List<T>();
foreach (Type type in Assembly.GetAssembly(typeof(T)).GetTypes()
.Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
{
objects.Add((T)Activator.CreateInstance(type, constructorArgs));
}
// If the classes implement IComparable then their objects could be sorted, see Where clause in signature
//objects.Sort();
return objects;
}
public static IEnumerable<string> GetNamesDerivedFromType<T>(params object[] constructorArgs) where T : class
{
List<string> names = new List<string>();
foreach (Type type in Assembly.GetAssembly(typeof(T)).GetTypes()
.Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
{
names.Add(((T)Activator.CreateInstance(type, constructorArgs)).ToString());
}
names.Sort();
return names;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment