0

During runtime, I would like to populate a drop down list with classes that have extended my base class. Currently I have an enum, and this is what I use to populate that list, but I want to add additional classes (and other people are adding classes) and do not want to have to maintain an enum for this purpose. I would like to add a new class and magically (reflection possibly) that class appears in the list without any addition code written for the drop down, or any additional enum added.

class Animal { ... }

enum AllAnimals { Cat, Dog, Pig };
class Cat : Animal {...}
class Dog : Animal {...}
class Pig : Animal {...}

Is there a way to accomplish this?

Tizz
  • 820
  • 1
  • 15
  • 31
  • 1
    Please don't just ask us to solve the problem for you. Show us how _you_ tried to solve the problem yourself, then show us _exactly_ what the result was, and tell us why you feel it didn't work. See "[What Have You Tried?](http://whathaveyoutried.com/)" for an excellent article that you _really need to read_. – John Saunders Jul 28 '14 at 16:25
  • Yes there is a way to accomplish this. Please use Google and make an attempt at it yourself. Then if it doesn't work come back with your code and the error message(s) you're getting and we'll try to assist. – Craig W. Jul 28 '14 at 16:26
  • Are the derived classes all guaranteed to be in the same assembly? – Steve Guidi Jul 28 '14 at 16:30
  • 2
    possible duplicate of [Get all derived types of a type](http://stackoverflow.com/questions/857705/get-all-derived-types-of-a-type) + [Get all inherited classes of an abstract class](http://stackoverflow.com/questions/5411694/get-all-inherited-classes-of-an-abstract-class) – Alex K. Jul 28 '14 at 16:30

1 Answers1

1

Use reflection to get the loaded assemblies and then enumerate through all types that are a subclass of your base class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            var types = new List<Type>();

            foreach (var assembly in assemblies)
                types.AddRange(assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(Animal))));

            foreach (var item in types)
                Console.WriteLine(item.Name);
        }
    }

    class Animal { }

    enum AllAnimals { Cat, Dog, Pig };
    class Cat : Animal { }
    class Dog : Animal { }
    class Pig : Animal { }
}
Martin
  • 1,634
  • 1
  • 11
  • 24
  • Why would you load the assembly again? It's already loaded. This also assumes all subclasses are in the same assembly. – Ryan Emerle Jul 28 '14 at 16:34