Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two objects' properties to find differences?

Tags:

c#

.net

I have two objects of the same type, and I want to loop through the public properties on each of them and alert the user about which properties don't match.

Is it possible to do this without knowing what properties the object contains?

like image 604
Gavin Avatar asked Jun 05 '09 19:06

Gavin


People also ask

How do you compare two values of objects?

In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity.

Can you use == to compare objects?

The == operator compares whether two object references point to the same object.

How do I find the difference between two objects in C#?

The Equals method and the IEquatable<T> interface could be used to know if two objects are equal but they won't allow you to know the differences between the objects. You could use reflection by comparing each property values.


2 Answers

Yes, with reflection - assuming each property type implements Equals appropriately. An alternative would be to use ReflectiveEquals recursively for all but some known types, but that gets tricky.

public bool ReflectiveEquals(object first, object second)
{
    if (first == null && second == null)
    {
        return true;
    }
    if (first == null || second == null)
    {
        return false;
    }
    Type firstType = first.GetType();
    if (second.GetType() != firstType)
    {
        return false; // Or throw an exception
    }
    // This will only use public properties. Is that enough?
    foreach (PropertyInfo propertyInfo in firstType.GetProperties())
    {
        if (propertyInfo.CanRead)
        {
            object firstValue = propertyInfo.GetValue(first, null);
            object secondValue = propertyInfo.GetValue(second, null);
            if (!object.Equals(firstValue, secondValue))
            {
                return false;
            }
        }
    }
    return true;
}
like image 174
Jon Skeet Avatar answered Sep 29 '22 04:09

Jon Skeet


Sure you can with reflection. Here is the code to grab the properties off of a given type.

var info = typeof(SomeType).GetProperties();

If you can give more info on what you're comparing about the properties we can get together a basic diffing algorithmn. This code for intstance will diff on names

public bool AreDifferent(Type t1, Type t2) {
  var list1 = t1.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
  var list2 = t2.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
  return list1.SequenceEqual(list2);
}
like image 36
JaredPar Avatar answered Sep 29 '22 03:09

JaredPar