0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, obj will always be the same type. Can you show me how to cast that into a format which can be used with .GetProperty("ID").GetValue()? In other words, can I get this property by string, how?
@ZeeTee: No, you're not going to be able to use GetProperty on that object, because it doesn't have that property from a CLR perspective. If you know which properties you're going to potentially want, you could create an anonymous type with all of them, fetched dynamically: new { obj.ID, obj.Foo, obj.Bar } and then that type will have all the properties you need. We don't really know what your context is, which makes it hard to give more of an answer.
Ok, so I have to build my own object to handle this operation. Oh well, I'll take it as a valid answer. You almost have 1m points man! wow!
Actually, I was able to access the property by index like this obj[0], so this resolved it.
@ZeeTee: That sounds like it could be fragile in the future... I wouldn't assume any particular ordering if you can help it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.