Wednesday, March 30, 2011

How do I get all the bottom types in an assembly?

This is sister question to this one

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 Employee, Freshman, and StudentList?

I'd like to be able to enumerate all the bottom types for any given assembly like the example above.

Thanks for your time :)

From stackoverflow
  • So you want to find all the types which no other type in the assembly derives from, right?

    (Refactored for readability.)

    var allTypes = assembly.GetTypes();
    var baseTypes = allTypes.Select(type => type.BaseType);
    var bottomTypes = allTypes.Except(baseTypes);
    

    (Let me know if you want a .NET 2.0 version. It'll be a bit more painful.)

    TheDeeno : Thanks Jon. This looks good.

0 comments:

Post a Comment