I don’t know if there’s a more elegant way with dynamically created objects, but using plain old reflection should work:
var nameOfProperty = "property1";
var propertyInfo = myObject.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);
GetProperty
will return null
if the type of myObject
does not contain a public property with this name.
EDIT: If the object is not a “regular” object but something implementing IDynamicMetaObjectProvider
, this approach will not work. Please have a look at this question instead:
- How do I reflect over the members of dynamic object?