0

Here is a problem:

There is a parent class Class01 which has 2 subclasses: Subclass0101 and Subclass0102. Class01 and its subclasses are not instantiated yet. We need to

  1. Enumerate all subclasses in Class01.
  2. Put them into the list collection and output the content of that collection.
  3. Make that as much generic as possible, using the name of the parent class (like <Class1> or so - I am not sure if the notation is correct). That is so that this method would be universal if we have Class02 with subclasses SubClass0201 and SubClass0202.

Would you be so kind to help we with the code composition as I was unable to compose the existing answers into one project? Thank you very-very much in advance!!!

Here are my intentions:

namespace Temp
{
    class Program
    {
        static void Main(string[] args)
        {

        // Not sure what to put here
        Show<Class01>

        // Not sure what to put here
        public static Show<T1>
        {
            // and here
        }
    }

    class Class01 {}

    class SubClass0101 : Class01 {}

    class SubClass0102 : Class01 { }

    class Class02 { }

    class SubClass0201 : Class02 { }

    class SubClass0202 : Class02 { }
}
Tracey23
  • 23
  • 6

1 Answers1

1

Assuming the subclasses are in the same assembly:

public static IEnumerable<Type> GetAllSubTypesInSameAssembly(this Type type)
{
    return type.Assembly
               .GetTypes()
               .Where(t => t != type && type.IsAssignableFrom(t));
}
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158