2

I try to add an element to a List I retrieved through reflection.

The following line

property.PropertyType.GetMethod("Add").Invoke(entity, new[] { innerValue });

is throwing an error

Object does not match target type" (Reflection.TargetException)

But the Types should match:

string listType=property.PropertyType().FullName; // System.Collections.Generic.List`1[[My.Entities.Task, My.Entities, Version=1.4.6429.20475, Culture=neutral, PublicKeyToken=null]]
string elementType=innerValue.GetType().FullName; // My.Entities.Task

entity is an object that contains the property above

What is wrong here?

1 Answer 1

7

You try to invoke Add on entitiy, not on the list contained in entity's property.

Get the value of the property (which should be the list) and invoke Add on that reference:

var list = property.GetValue(entity);
property.PropertyType.GetMethod("Add").Invoke(list, new[] { innerValue });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.