Reputation: 13233
I have a dynamic object that is generated from WebMatrix.Data:
dynamic obj; [WebMatrix.Data.DynamicRecord]
So doing something like this is fine:
int ID = obj.ID;
However, trying to access the property by string like this:
obj.GetType().GetProperty("ID").GetValue(obj, null);
and I gets the following error: Cannot perform runtime binding on a null reference
I am assuming the WebMatrix.Data.DynamicRecord
type is not used the same as the dynamic
type? But it is declared as dynamic
.
The following does return a type of WebMatrix.Data.DynamicRecord
w/ a whole array of values:
obj.GetType();
However, the following returns a type of dynamic
with value of null
:
obj.GetType().GetProperty("ID");
I'm guessing that's why the error, but why is it null when obj.ID
does not return null
?
How do I get the property by string?
Upvotes: 0
Views: 498
Reputation: 1500665
I'm guessing that's why the error, but why is it null when obj.ID does not return null?
GetProperty()
will look for a CLR property on the type. That's not always how a dynamic property access works - DynamicRecord
derives from DynamicObject
, and I suspect it overrides the TryGetMember
method which is used for property access (amongst other things). So basically, this is a property which is only available dynamically.
If you know that obj
will always be a DynamicObject
, you could always cast to that and call TryGetMember
yourself... although you'd have to create your own GetMemberBinder
. That's slightly awkward, but it looks like the only abstract member is FallbackGetMember
, so you'd just need to work out how to implement that.
Upvotes: 1