1

I have a list of dynamic and I am trying to get value from a property using reflection. The code goes like this:

var list = new List<Employee>();
list.Add(new Employee {FirstName="Krishna"});
IEnumerable<dynamic> data = list;

In Employee, lets say I have property called FirstName,

 Type type = data.GetType().GetGenericArguments()[0];
 PropertyInfo property = type.GetProperty( "FirstName" );

Now, how do I get value from this property? I tried:

 object value = property.GetValue( data, null ); 

But it gives me error saying object doesnot match target type.

KrishnaDhungana
  • 2,604
  • 4
  • 25
  • 37
  • 1
    Check type before using it http://stackoverflow.com/questions/10379968/listobject-vs-listdynamic – ray Dec 08 '13 at 09:26

2 Answers2

2

You have to send to property.GetValue function the object you want to get its value

like: data[0]

Replace your line with : object value = property.GetValue(data[0], null); this will return the FirstName of the first element in the list.

Hadas
  • 10,188
  • 1
  • 22
  • 31
1

Here for all the dynamic objects method are same but as you have to access data from list so it looks like as follows :

data.GetType().GetProperty("visible").GetValue(data[i],null);

You can do directly Typecast and save in your type data.

rhatwar007
  • 343
  • 3
  • 14