title: C# - GetValue - Object Does Not Match Target Type
body: <p>I am trying to write a generic method to compare two objects (I purposefully have two different types coming in. The second one has the same properties as the first one. The first just has more.).</p>
  
  <p>I want to make sure the properties have the same values. The following code works for most of the properties that I have in the objects, but occasionally it throws the:</p>
  
  <blockquote>
    <p>"Object Does Not Match Target Type"</p>
  </blockquote>
  
  <p>...error at</p>
  
  <p><code>var valFirst = prop.GetValue(manuallyCreated, null) as IComparable;</code></p>
  
  <pre><code>public static bool SameCompare&lt;T, T2&gt;(T manuallyCreated, T2 generated){
  var propertiesForGenerated = generated.GetType().GetProperties();
  int compareValue = 0;
  
  foreach (var prop in propertiesForGenerated) {
  
      var valFirst = prop.GetValue(manuallyCreated, null) as IComparable;
      var valSecond = prop.GetValue(generated, null) as IComparable;
      if (valFirst == null &amp;&amp; valSecond == null)
          continue;
      else if (valFirst == null) {
          System.Diagnostics.Debug.WriteLine(prop + "s are not equal");
          return false;
      }
      else if (valSecond == null) {
          System.Diagnostics.Debug.WriteLine(prop + "s are not equal");
          return false;
      }
      else if (prop.PropertyType == typeof(System.DateTime)) {
          TimeSpan timeDiff = (DateTime)valFirst - (DateTime)valSecond;
          if (timeDiff.Seconds != 0) {
              System.Diagnostics.Debug.WriteLine(prop + "s are not equal");
              return false;
          }
      }
      else
          compareValue = valFirst.CompareTo(valSecond);
      if (compareValue != 0) {
          System.Diagnostics.Debug.WriteLine(prop + "s are not equal");
          return false;
      }
  }
  
  System.Diagnostics.Debug.WriteLine("All values are equal");
  return true;
  }
  </code></pre>