views:

68

answers:

1

I've got a Customer object with a Collection of CustomerContacts

IEnumerable<CustomerContact> Contacts { get; set; }

In some other code I'm using Reflection and have the PropertyInfo of Contacts property

var contacts = propertyInfo.GetValue(customerObject, null);

I know contacts has at least one object in it, but how do I get it out? I don't want to Cast it to IEnumerable<CustomerContact> because I want to keep my reflection method dynamic. I thought about calling FirstOrDefault() by reflection - but can't do that easily because its an extension method.

Does anyone have any ideas?

+6  A: 

If you really want to avoid mentioning CustomerContact in your code, you could do this:

IEnumerable items = (IEnumerable)propertyInfo.GetValue(customerObject, null);

object first = items.Cast<object>().FirstOrDefault();
dtb
This is nicer than mine...
Reed Copsey
Thank you, just what I needed.
Andy Clarke