Skip to content

Instantly share code, notes, and snippets.

@omni-
Last active August 29, 2015 14:02
Show Gist options
  • Save omni-/f531d9f2759bf035b687 to your computer and use it in GitHub Desktop.
Save omni-/f531d9f2759bf035b687 to your computer and use it in GitHub Desktop.
Get all derived classes
public static IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs)
{
return Assembly.GetAssembly(typeof (T)).GetTypes().Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof (T))).Select(type => (T) Activator.CreateInstance(type, constructorArgs)).ToList();
}
@omni-
Copy link
Author

omni- commented Jun 6, 2014

This function can be used to get all derived classes of a parent type
usage:

public class Parent { }

public class Child1 : Parent { }

public class Child2 : Parent { }

class Program
{
    static void Main(string[] args)
    {
        var output = GetEnumerableOfType<Parent>();
        foreach (var x in output)
        {
            Console.Writeline(x.ToString());
        }
    }
    public static IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs)
    {
        return Assembly.GetAssembly(typeof (T)).GetTypes().Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof (T))).Select(type => (T) Activator.CreateInstance(type, constructorArgs)).ToList();
    }
}

output:

Child1

Child2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment