views:

234

answers:

2

So if I have an instance of

System.Reflection.Assembly

and I have the following model:

class Person {}
class Student : Person {}
class Freshman : Student {}
class Employee : Person {}
class PersonList : ArrayList {}
class StudentList : PersonList {}

How can I enumerate the assembly's types to get a reference to only the Person and PersonList types?

To be clear: I don't want to ever explicitly specify the Person or PersonList type during this lookup. Person and PersonList are just the root type defined in the assembly in question for this example. I'm shooting for a general way to enumerate all the root types for a given assembly.

Thank for your time :)

+6  A: 

How about:

var rootTypes = from type in assembly.GetTypes()
                where type.IsClass && type.BaseType == typeof(object)
                select type;

? Or in non-LINQ terms:

foreach (Type type in assembly.GetTypes())
{
    if (type.IsClass && type.BaseType == typeof(object))
    {
        Console.WriteLine(type);
    }
}

EDIT: No, that wouldn't spot PersonList. You'll need to be clearer about the definition of "root". Do you actually mean "any type whose base type isn't in the same assembly"? If so:

var rootTypes = from type in assembly.GetTypes()
                where type.IsClass && type.BaseType.Assembly != assembly
                select type;
Jon Skeet
If the assembly had PersonList as a root type which inherited from ArrayList would this still work?
TheDeeno
updated question to reflect this.
TheDeeno
Sorry about not being clear. Wasn't sure how to ask this one. The second half of the answer looks great. Will try. Thanks.
TheDeeno
A: 

The only way I see this happening is actually specifying the base types that your "base types" inherit from and then plugging those types into a check similar to the code that Jon already posted as well as checking the namespace they are from.

If you'd like an example let me know, but you will have to manually specify the framework base types that your base types inherit from.

Quintin Robinson