Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use FastMember to get the properties of a dynamic object?

I have the following object:

dynamic person = new {Id = 1, Name = "SpiderMan"};

I need to be able to iterate through the property names e.g. "Id", "Name".

I also need to be able to achieve this in the most efficient way therefore I chose to use FastMember however it's api does not allow me to iterate through the properties.

Any ideas?

[UPDATE]

Thanks to Marc I managed to achieve what I wanted using:

dynamic person = new { Id = 1, Name = "SpiderMan" };
MemberSet members = TypeAccessor.Create(person.GetType()).GetMembers();
foreach (Member item in members)
{
    // do whatever
}
like image 923
MaYaN Avatar asked Aug 27 '15 21:08

MaYaN


1 Answers

For the scenario you show, TypeAccessor.Create(obj.GetType()) and GetMember() should work fine, since that type is fine for reflection.

In the more general case: that's a fair question - I honestly can't remember whether FastMember exposes this for true dynamic types, but one important consideration here is that by the very nature of dynamic objects, the set of properties may not even be enumerable - i.e. the code could respond to obj.Whatever on the fly, without knowing about Whatever in advance. For the object you actually have, however, simple reflection is your best bet. The scenario you show does not need dynamic.

like image 57
Marc Gravell Avatar answered Sep 22 '22 09:09

Marc Gravell