title: Add to a collection of unknown type using reflection in c#
body: <p>So I am using reflection to loop through the properties of one object and populating the values on a different object with properties of the same name. This works great but the problem comes when the property type is a collection. I want to be able to loop through each of the objects in the source collection and populate the same list with objects in the source collection.</p>
  
  <pre><code>public class SourceMessage
  {
      public string Name { get; set; }
      public int Version { get; set; }
      public IList&lt;ValueDefinition&gt; Values { get; set; }
  }
  
  public class ValueDefinition
  {
      public string Name { get; set; }
      public string Value { get; set; }
  }
  
  public class TargetObject
  {
      public TargetObject()
      {
          Values = new List&lt;TargetValueDefinition&gt;();
      }
      public string Name { get; set; }
      public int Version { get; set; }
      public IList&lt;TargetValueDefinition&gt; Values { get; set; }
  }
  
  public class TargetValueDefinition
  {
      public string Name { get; set; }
      public string Value { get; set; }
  }
  </code></pre>
  
  <p>Then I use Reflection to populate the target from the source.</p>
  
  <pre><code>public static void PopulateFromMessage&lt;T, TS&gt;(ref T targetEntity, TS message)
  {
      var sourceType = typeof(TS);
      var targetType = typeof(T);
  
      foreach (var targetPropInfo in targetType.GetProperties())
      {
          if (sourceType.GetProperty(targetPropInfo.Name) != null)
          {
              var obj = sourceType.GetProperty(targetPropInfo.Name);
              if (obj.PropertyType.Namespace == "System.Collections.Generic")
              {
                  //var x = targetType.GetProperty(targetPropInfo.Name);
                  //PopulateFromMessage(ref x, sourceType.GetProperty(targetPropInfo.Name));
                  continue;
              }
              targetPropInfo.SetValue(targetEntity, sourceType.GetProperty(targetPropInfo.Name).GetValue(message), null);
          }
      }
  }
  </code></pre>
  
  <p>So calling this would be like this:</p>
  
  <pre><code>private void DenormalizeMessage(SourceMessage message)
  {
      var newTargetObject = new TargetObject();
      PopulateFromMessage(ref newTargetObject , message);
  }
  </code></pre>
  
  <p>I can identify when the property is a collection but am uncertain of how to create new TargetValueDefinitions and populate them with the values from ValueDefinitions. In the end it is pretty much a copy of the SourceMessage in the form of a TargetObject. </p>
  
  <p>This all stems from receiving messages and transforming them into objects with the same property names.</p>