Get value of c# dynamic property via string

TimDog picture TimDog · Feb 8, 2011 · Viewed 242.1k times · Source

I'd like to access the value of a dynamic c# property with a string:

dynamic d = new { value1 = "some", value2 = "random", value3 = "value" };

How can I get the value of d.value2 ("random") if I only have "value2" as a string? In javascript, I could do d["value2"] to access the value ("random"), but I'm not sure how to do this with c# and reflection. The closest I've come is this:

d.GetType().GetProperty("value2") ... but I don't know how to get the actual value from that.

As always, thanks for your help!

Answer

Adam Robinson picture Adam Robinson · Feb 9, 2011

Once you have your PropertyInfo (from GetProperty), you need to call GetValue and pass in the instance that you want to get the value from. In your case:

d.GetType().GetProperty("value2").GetValue(d, null);