0

How to dynamically obtain all non-generic classes that inherit from the Person class (Student, Teacher) and properties (Address) for the Person class.

Example code:

 [DataContract]
 [KnownType(typeof(Student))]
 [KnownType(typeof(Teacher))]
 public abstract class Person {
     [DataMember]
     public string Name { get; set; }

     [DataMember]
     public string Surname { get; set; }

     [DataMember]
     public Address _Address { get; set; }
 }
Xatep
  • 353
  • 1
  • 5
  • 11
  • Do you mean other non-generic classes that inherit from Person? Or do you mean all non-generic properties of the Person class? – Maarten Jul 11 '12 at 12:07
  • I mean both non-generic classes that inherit from the Person class and all non-generic properties :) – Xatep Jul 11 '12 at 12:09
  • Look at this Thread: http://stackoverflow.com/questions/5411694/get-all-inherited-classes-of-an-abstract-class – speti43 Jul 11 '12 at 12:35

2 Answers2

1
var nonGenericProperties = typeof(Person)
    .GetProperties()
    .Where(p => !p.IsGenericType)
    .ToList();

var nonGenericClassesWhichInheritFromPerson = Assembly.GetAssembly(typeof(Person))
    .GetTypes()
    .Where(t => t.IsSubclassOf(typeof(Person))
    .ToList()

The second query only checks for derived types in the same assembly.

Maarten
  • 22,527
  • 3
  • 47
  • 68
0

To look for all classes that inherit Person, you need to define where you are looking. You can't look everywhere. Suppose that all classes are in the same assembly as the Person class you can write that:

Assembly.GetAssembly(typeof(Person)).GetTypes().Where(t => typeof(Person).IsAssignableFrom(t) && !t.ContainsGenericParameters);

As for the properties, do the same in a foreach loop on all properties:

foreach (var pi in typeof(Person).GetProperties())
{
// Do the same for pi.PropertyType
}
Amiram Korach
  • 13,056
  • 3
  • 28
  • 30