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

1

12

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
}
Marvelous answered 27/8, 2015 at 21:49 Comment(0)
C
12

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.

Curcuma answered 27/8, 2015 at 22:16 Comment(1)
Tnx Marc, GetMembers() works great for my scenario. Any plans for migrating the source code from GoogleCode over to GitHub? Once again tnx for this brilliant library.Marvelous

© 2022 - 2024 — McMap. All rights reserved.