Guillaume Slashy
Guillaume Slashy

Reputation: 3624

Dynamically access to a PropertyInfo whose Type is IEnumerable<customClass>

I got this code thats works :

var assembly= Assembly.LoadFrom("D:\\...\\mydll.dll");
Type rmType = assembly.GetType(specific_class_with_namespace);
bject MyObjj = Activator.CreateInstance(rmType);
PropertyInfo[] pi = rmType.GetProperties();

foreach(PropertyInfo prop in pi)
{
    Console.WriteLine("Prop: {0}",  prop.Name);
}

The thing is that the property I wanna access to is a IEnumerable<IWidget>, where IWidget is an internal class of my dll. So in my current code I can't test the Type of my PropertyInfo (and cast it right ? :/) The final objective is to access to the Name property of my IWidget. Something like :

foreach(var widget in myProperty)
{
    string widgetName = widget.Name;
}

I read a couple of tutorials on the web and some questions here on SO, but none helped me for my IEnumerable<customType> problem :/

EDIT :

when I do :

PropertyInfo ItemsProperty = rmType.GetProperty("Items");
var ItemsPropertyValue = ItemsProperty.GetValue(rmType, null);

I can a XamlParseException with the "most" InnerException being "Object does not match target type"...

Upvotes: 3

Views: 635

Answers (1)

Piotr Auguscik
Piotr Auguscik

Reputation: 3681

You can test you property for being of type IEnumerable and then in foreach loop with reflection you can access property of item with name Name.

To test for being IEnumerable you can use typeof(IEnumerable).IsAssignableFrom(prop.PropertyType) or type.GetGenericTypeDefinition() == typeof(IEnumerable<>).

EDIT:

In GetValue you should put instance not the type:

var ItemsPropertyValue = ItemsProperty.GetValue(MyObjj, null);

Upvotes: 1

Related Questions