Imagine that I have a dynamic variable:
dynamic d = *something*
Now, I create properties for d
which I have on the other hand from a string array:
string[] strarray = { 'property1','property2',..... }
I don't know the property names in advance.
How in code, once d
is created and strarray is pulled from DB, can I get the values?
I want to get d.property1 , d.property2
.
I see that the object has a _dictionary
internal dictionary that contains the keys and the values, how do I retrieve them?
GetValue(Object) Returns the property value of a specified object.
GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[]) Searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints. GetProperty(String) Searches for the public property with the specified name.
< Previous Next > The PropertyInfo class discovers the attributes of a property and provides access to property metadata. The PropertyInfo class is very similar to the FieldInfo class and also contains the ability to set the value of the property on an instance.
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:
This will give you all property names and values defined in your dynamic variable.
dynamic d = { // your code }; object o = d; string[] propertyNames = o.GetType().GetProperties().Select(p => p.Name).ToArray(); foreach (var prop in propertyNames) { object propValue = o.GetType().GetProperty(prop).GetValue(o, null); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With