Daniel Schobel
Daniel Schobel

Reputation: 506

Best way to access a member of a dynamic object when I know the member name?

Given a dynamic object and a string member name:

string AMemberNameIKnowExists = "SomeMember"; //determined at runtime
dynamic myDynamicObject = //...

I want to access the "SomeMember" member on my dynamic object. Do I have to use the standard reflection tools or does the fact that I have a dynamic object give me a better way to resolve a member by name?

Upvotes: 4

Views: 460

Answers (2)

phipsgabler
phipsgabler

Reputation: 20970

I haven't tested this, but you should be able to use DynamicObject's TryGetMember method:

myDynamicObject.TryGetMember(new GetMemberBinder("SomeMember", false), out result)

As far as I understood dynamic, that's what a dynamic call like myDynamicObject.SomeMember gets translated to.

Upvotes: 2

Pranay Rana
Pranay Rana

Reputation: 176956

Try this way to get property value form the object

myDynamicObject.GetType()
               .GetProperty("SomeMember")
               .GetValue(myDynamicObject, null);

Upvotes: 0

Related Questions