How to get property value of a dynamic type where property name is in a variable in C#
<p>I am trying to get the value of a property of a dynamic object. The json string is parsed/deserialized into a dynamic object and then I want to access the property by name followed by the get value.</p>

<pre><code>string json = "{\"key1\":\"value1\", \"key2\": \"value2\"}";
dynamic d = JObject.Parse(json);
Console.WriteLine("Key1 : " + d.key1); //value1
</code></pre>

<p>Above code works as expected but how to get the value using get property by name that is stored in a variable?</p>

<pre><code>string jsonKey = "key2";
string json = "{\"key1\":\"value1\", \"key2\": \"value2\"}";
dynamic d = JObject.Parse(json);
var jsonValue = d.GetType().GetProperty(jsonKey).GetValue(d, null); //throws exception - Cannot perform runtime binding on a null reference
Console.WriteLine("jsonValue : " + jsonValue);
</code></pre>

<p><code>GetProperty(jsonKey)</code> throws an exception <code>Cannot perform runtime binding on a null reference</code></p>

<p>Or, if there is an alternative solution to this problem.</p>