Jyina
Jyina

Reputation: 2902

How to get the type of an object in a collection of objects at runtime?

In my code I get the type of an object (Party object) in a for loop and get the property info of a particular property "firstname". All the objects in the Parties[] collection return the same type so I would like to get the type outside of do while loop only once and still need to be able to get the property "firstname" from the correct party object. Is it possible to do this way? Thanks for any help.

public List<Party> Parties { get; set; }

PropertyInfo info = null;

i = 1
do
{

    foreach (Field field in TotalFields)
    {

        info = Parties[i - 1].GetType().GetProperty("firstname");

        //some other code here

    }
i++;
} while (i <= Parties.Count);

Upvotes: 0

Views: 122

Answers (1)

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158389

When you get the value for a property through a PropertyInfo object, you need to pass an object instance from which to fetch the value. This means that you can reuse the same PropertyInfo instance for several objects, given that they are of the same type as the PropertyInfo was created for:

// Note how we get the PropertyInfo from the Type itself, not an object 
// instance of that type.
PropertyInfo propInfo = typeof(YourType).GetProperty("SomeProperty");

foreach (YourType item in SomeList)
{
    // this assumes that YourType.SomeProperty is a string, just as an example
    string value = (string)propInfo.GetValue(item, null);
    // do something sensible with value
}

Your question is tagged as being C# 3, but for completeness it's worth mentioning that this can be made somewhat simpler in C# 4 by using dynamic:

foreach (dynamic item in SomeList)
{
    string value = item.SomeProperty;
    // do something sensible with value
}

Upvotes: 1

Related Questions