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

C#Reflection.Net 4.0

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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:

Solution 2 - C#

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);
}

Solution 3 - C#

Hope this would help you:

public static object GetProperty(object o, string member)
{
	if(o == null) throw new ArgumentNullException("o");
	if(member == null) throw new ArgumentNullException("member");
	Type scope = o.GetType();
	IDynamicMetaObjectProvider provider = o as IDynamicMetaObjectProvider;
	if(provider != null)
	{
		ParameterExpression param = Expression.Parameter(typeof(object));
		DynamicMetaObject mobj = provider.GetMetaObject(param);
		GetMemberBinder binder = (GetMemberBinder)Microsoft.CSharp.RuntimeBinder.Binder.GetMember(0, member, scope, new CSharpArgumentInfo[]{CSharpArgumentInfo.Create(0, null)});
		DynamicMetaObject ret = mobj.BindGetMember(binder);
		BlockExpression final = Expression.Block(
			Expression.Label(CallSiteBinder.UpdateLabel),
			ret.Expression
		);
		LambdaExpression lambda = Expression.Lambda(final, param);
		Delegate del = lambda.Compile();
		return del.DynamicInvoke(o);
	}else{
		return o.GetType().GetProperty(member, BindingFlags.Public | BindingFlags.Instance).GetValue(o, null);
	}
}

Solution 4 - C#

Use the following code to get Name and Value of a dynamic object's property.

dynamic d = new { Property1= "Value1", Property2= "Value2"};

var properties = d.GetType().GetProperties();
foreach (var property in properties)
{
    var PropertyName=property.Name; 
//You get "Property1" as a result
 
  var PropetyValue=d.GetType().GetProperty(property.Name).GetValue(d, null); 
//You get "Value1" as a result

// you can use the PropertyName and Value here
 }

Solution 5 - C#

string json = w.JSON;

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

DynamicJsonConverter.DynamicJsonObject obj = 
      (DynamicJsonConverter.DynamicJsonObject)serializer.Deserialize(json, typeof(object));

Now obj._Dictionary contains a dictionary. Perfect!

This code must be used in conjunction with https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object

  • make the _dictionary variable from "private readonly" to public in the code there

Solution 6 - C#

Did you see ExpandoObject class?

Directly from MSDN description: "Represents an object whose members can be dynamically added and removed at run time."

With it you can write code like this:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");

Solution 7 - C#

IF d was created by Newtonsoft you can use this to read property names and values:

    foreach (JProperty property in d)
    {
        DoSomething(property.Name, property.Value);
    }

Solution 8 - C#

Getting value data from a dynamic objects using property(string).

var nameOfProperty = "chairs";
var propertyInfo = model.assets.GetType().GetField(nameOfProperty).GetValue(model.assets);

Solution 9 - C#

Thought this might help someone in the future.

If you know the property name already, you can do something like the following:

[HttpPost]
[Route("myRoute")]
public object SomeApiControllerMethod([FromBody] dynamic args){
   var stringValue = args.MyPropertyName.ToString();
   //do something with the string value.  If this is an int, we can int.Parse it, or if it's a string, we can just use it directly.
   //some more code here....
   return stringValue;
}

Solution 10 - C#

Say you have anonymous type in service result.Value, with class errorCode and property ErrorMessage, and needed to get the value of ErrorMessage, could get it in one-liner like this using dynamic:

var resVal = (dynamic)result.Value; var errMsg = resVal.GetType().GetProperty("errorCode").GetValue(resVal, null).ErrorMessage;

Solution 11 - C#

you can try like this:

d?.property1 , d?.property2

I have tested it and working with .netcore 2.1

Solution 12 - C#

you can use "dynamicObject.PropertyName.Value" to get value of dynamic property directly.

Example :

d.property11.Value

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsergata.NET LTDView Question on Stackoverflow
Solution 1 - C#HeinziView Answer on Stackoverflow
Solution 2 - C#Tomislav MarkovskiView Answer on Stackoverflow
Solution 3 - C#IS4View Answer on Stackoverflow
Solution 4 - C#GhebrehiywetView Answer on Stackoverflow
Solution 5 - C#sergata.NET LTDView Answer on Stackoverflow
Solution 6 - C#ADIMOView Answer on Stackoverflow
Solution 7 - C#user3285954View Answer on Stackoverflow
Solution 8 - C#Rajesh KalavakuntaView Answer on Stackoverflow
Solution 9 - C#cr1ptoView Answer on Stackoverflow
Solution 10 - C#Siggi HergeirsView Answer on Stackoverflow
Solution 11 - C#Deepak ShawView Answer on Stackoverflow
Solution 12 - C#abhishek shetyeView Answer on Stackoverflow