Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get property value from C# dynamic object by string (reflection?)

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?

like image 888
sergata.NET LTD Avatar asked Dec 25 '11 20:12

sergata.NET LTD


People also ask

What does GetValue return c#?

GetValue(Object) Returns the property value of a specified object.

What is GetProperty C#?

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.

What is PropertyInfo?

< 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.


2 Answers

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?
like image 174
Heinzi Avatar answered Sep 21 '22 08:09

Heinzi


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); } 
like image 35
Tomislav Markovski Avatar answered Sep 20 '22 08:09

Tomislav Markovski