Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As is the code will not do what you are expecting.</p> <p>Try this simple test:</p> <pre><code> class A { public int Id { get; set; } public string Name { get; set; } } class B : A { public DateTime BirthDate { get; set; } } class ObjectComparer { public static void Show() { A a = new A(); B b = new B(); A a1 = new A(); Console.WriteLine(ObjectComparator.CompareProperties(a, b)); Console.WriteLine(ObjectComparator.CompareProperties(b, a)); Console.WriteLine(ObjectComparator.CompareProperties(a, a1)); } } </code></pre> <p>You would expect it to return</p> <p>false</p> <p>false</p> <p>true</p> <p>but it returns</p> <p>false</p> <p>false</p> <p>false</p> <p>try changing the inner if to look like:</p> <pre><code> if (!object.Equals(newProperty.GetValue(newObject, null), oldProperty.GetValue(oldObject, null))) { return false; } </code></pre> <p>You can also save some time in the case a and a1 both reference the same object by checking that in the begining of the method.</p> <pre><code> static class ObjectComparator { public static bool CompareProperties(T newObject, T oldObject) { if (object.Equals(newObject, oldObject)) { return true; } if (newObject.GetType().GetProperties().Length != oldObject.GetType().GetProperties().Length) { return false; } else { var oldProperties = oldObject.GetType().GetProperties(); foreach (PropertyInfo newProperty in newObject.GetType().GetProperties()) { try { PropertyInfo oldProperty = oldProperties.Single(pi => pi.Name == newProperty.Name); if (!object.Equals(newProperty.GetValue(newObject, null), oldProperty.GetValue(oldObject, null))) { return false; } } catch { return false; } } return true; } } } </code></pre> <p>If you are concered with performance, you can cache the return of Type.GetProperties into a local variable during the lifetime of the method, since Reflection does not do that by itself at least up to version 3.5 SP1. In doing that you will drop GetProperties calls from four to two.</p> <p>If you are only expecting to compare objects of exactly the same type (or put another way not compare between base and derived instances), you can further reduce the calls of GetProperties to one.</p> <p>Hope this helps.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload