Skip to content

Instantly share code, notes, and snippets.

@xepherys
Created September 6, 2021 17:38
Show Gist options
  • Save xepherys/0d90c9268e19d137c6db5ba1c82161d8 to your computer and use it in GitHub Desktop.
Save xepherys/0d90c9268e19d137c6db5ba1c82161d8 to your computer and use it in GitHub Desktop.
ReflectiveEnumerator - Enumerate classes inheriting from a specified abstract class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class ReflectiveEnumerator
{
/// <summary>
/// Original class from StackExchange post
/// https://stackoverflow.com/questions/5411694/get-all-inherited-classes-of-an-abstract-class/6944605#6944605
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="constructorArgs"></param>
/// <returns></returns>
public static IEnumerable<T> GetEnumerableOfType<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));
}
objects.Sort();
return objects;
}
/// <summary>
/// </summary>
/// <typeparam name="T">Parent type to find child class of.</typeparam>
/// <returns>Returns an IEnumerable of whatever type was supplied in the request.</returns>
public static IEnumerable<T> GetEnumerableOfType<T>() where T : class
{
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));
}
objects = objects.OrderBy(o => o.ToString()).ToList();
return objects;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment