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