title: C# - copying property values from one instance to another, different classes
body: <p>I have two C# classes that have many of the same properties (by name and type).  I want to be able to copy all non-null values from an instance of <code>Defect</code> into an instance of <code>DefectViewModel</code>.  I was hoping to do it with reflection, using <code>GetType().GetProperties()</code>.  I tried the following:</p>
  
  <pre><code>var defect = new Defect();
  var defectViewModel = new DefectViewModel();
  
  PropertyInfo[] defectProperties = defect.GetType().GetProperties();
  IEnumerable&lt;string&gt; viewModelPropertyNames =
      defectViewModel.GetType().GetProperties().Select(property =&gt; property.Name);
  
  IEnumerable&lt;PropertyInfo&gt; propertiesToCopy =
      defectProperties.Where(defectProperty =&gt;
          viewModelPropertyNames.Contains(defectProperty.Name)
      );
  
  foreach (PropertyInfo defectProperty in propertiesToCopy)
  {
      var defectValue = defectProperty.GetValue(defect, null) as string;
      if (null == defectValue)
      {
          continue;
      }
      // "System.Reflection.TargetException: Object does not match target type":
      defectProperty.SetValue(viewModel, defectValue, null);
  }
  </code></pre>
  
  <p>What would be the best way to do this?  Should I maintain separate lists of <code>Defect</code> properties and <code>DefectViewModel</code> properties so that I can do <code>viewModelProperty.SetValue(viewModel, defectValue, null)</code>?</p>
  
  <p><strong>Edit:</strong>  thanks to both <a href="https://stackoverflow.com/questions/3610891/c-copying-property-values-from-one-instance-to-another-different-classes/3610915#3610915">Jordão's</a> and <a href="https://stackoverflow.com/questions/3610891/c-copying-property-values-from-one-instance-to-another-different-classes/3610925#3610925">Dave's</a> answers, I chose AutoMapper.  <code>DefectViewModel</code> is in a WPF application, so I added the following <code>App</code> constructor:</p>
  
  <pre><code>public App()
  {
      Mapper.CreateMap&lt;Defect, DefectViewModel&gt;()
          .ForMember("PropertyOnlyInViewModel", options =&gt; options.Ignore())
          .ForMember("AnotherPropertyOnlyInViewModel", options =&gt; options.Ignore())
          .ForAllMembers(memberConfigExpr =&gt;
              memberConfigExpr.Condition(resContext =&gt;
                  resContext.SourceType.Equals(typeof(string)) &amp;&amp;
                  !resContext.IsSourceValueNull
              )
          );
  }
  </code></pre>
  
  <p>Then, instead of all that <code>PropertyInfo</code> business, I just have the following line:</p>
  
  <pre><code>var defect = new Defect();
  var defectViewModel = new DefectViewModel();
  Mapper.Map&lt;Defect, DefectViewModel&gt;(defect, defectViewModel);
  </code></pre>