Masoud
Masoud

Reputation: 8171

find inherited properties of a generic list elements using reflection

I have a generic List as:

IList<BaseEntity> list; //base entity is a public base class

also i have some other classes that inherited from BaseEntity:

public class Order:BaseEntity
{
    //Properties
}
public class Customer:BaseEntity
{
    //Properties
}
....
public class X:BaseEntity
{
    //Properties
}

my list filled with these inherited objects(Order,Customer,...). how can i find all properties of each element(include BaseEntity properties and inherited properties) in list using reflection?

Upvotes: 2

Views: 326

Answers (3)

lightbricko
lightbricko

Reputation: 2709

Simply use this for each item in the list:

item.GetType().GetProperties() or the GetProperties overload:

http://msdn.microsoft.com/en-us/library/system.type.getproperties.aspx

Upvotes: 0

quetzalcoatl
quetzalcoatl

Reputation: 33516

Every object in the .net world provides you with GetType method, so for every element in the list you can ask it for the set of its properties:

foreach(var item in list)
{
    var props = item.GetType().GetProperties();
    // props is a PropertyInfo[]
}

Each PropertyInfo carries many information like the PropertyName, the PropertyType(that is, what the Getter returns) and the DefinedBy (that is, which class defined it -- it may be this class or any base class of the inquired object).

See GetProperties. By default it returns only public properties, but considering you say 'entity' this will probably be what you want. But, if you need nonpublic properties too, then see GetProperties(BindingFlags).

Please note that this actually inquires each object in the list about its own properties. You will get N arrays of various properties of classes, not objects. If the 5th item is a Foo, then you will get an array of PropInfos for Foo class.

This not necessarily is the best way, as most probably the object types will be repeated in your list. You may want to first scan the list for distinct types and then inquire for properties only once per type.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

You can get all public properties of each object like this:

foreach (var e in list) {
    var type = e.GetType();
    Console.WriteLine("====== {0}", type.FullName);
    foreach (var p in type.GetProperties()) {
        Console.WriteLine(p);
    }
}

Here is a demo on ideone. GetProperties() produces a list of all public properties of your class. You can examine the names and the types of these properties using the PropertyInfo variable p. You can also get and set the properties themselves by calling var val = p.GetValue(e).

Upvotes: 2

Related Questions