title: Get a Dictionary Value Using Reflection
body: <p>I am trying to access an object stored in a dictionary of type String, UnknownClass. I have the key, and know the value is one of several container classes. Since the value is passed to a method that takes an object, I do not need to know the type of the class stored as a value. I also need to call ContainsKey to confirm the key exists.</p>
  
  <p>I have tried the following methods with no success:</p>
  
  <pre><code>Dictionary&lt;String, object&gt; list = (Dictionary&lt;String, object&gt;)source.GetType().GetProperty(dictionaryName).GetValue(source, null);
  nextSource = list[key];
  </code></pre>
  
  <p>Which gives me a casting error, and:</p>
  
  <pre><code>nextSource = source.GetType().GetMethod("get_Item").Invoke(source, new object[] { key });
  </code></pre>
  
  <p>Which gives me a null reference exception.</p>
  
  <p>Here is a bit more of the code, although I am not quite sure it will help much.</p>
  
  <pre><code>private void SetValue(object source, String path, String value)
  {
      if (path.Contains('.'))
      {
          //  If this is not the ending Property, continue recursing
          int index = path.IndexOf('.');
          String property = path.Substring(0, index);
  
          object nextSource;
          if(property.Contains("*"))
          {
              path = path.Substring(index + 1);
              index = path.IndexOf('.');
              String dictionaryName = path.Substring(0, index);
  
              Dictionary&lt;String, object&gt; list = (Dictionary&lt;String, object&gt;)source.GetType().GetProperty(dictionaryName).GetValue(source, null);
              nextSource = list[property.Substring(1)];
              //property = property.Substring(1);
              //nextSource = source.GetType().GetMethod("Item").Invoke(source, new[] { property });
          } ...
  </code></pre>
  
  <p>The dictionary being accessed is defined in the PersonObject class as such:</p>
  
  <pre><code>public class PersonObject
  {
      public String Name { get; set; }
      public AddressObject Address { get; set; }
      public Dictionary&lt;String, HobbyObject&gt; Hobbies { get; set; }
  </code></pre>
  
  <p>The value of Path, at this stage, is set to <code>"*Hiking.Hobbies.Hobby"</code>. Basically, the path string allows me to navigate to a Property in a subclass, and I need the Dictionary to access properties for a list of the same class.</p>