Finding property differences between two C# objects

C#.NetReflectionAuditing

C# Problem Overview


The project I'm working on needs some simple audit logging for when a user changes their email, billing address, etc. The objects we're working with are coming from different sources, one a WCF service, the other a web service.

I've implemented the following method using reflection to find changes to the properties on two different objects. This generates a list of the properties that have differences along with their old and new values.

public static IList GenerateAuditLogMessages(T originalObject, T changedObject)
{
IList list = new List();
string className = string.Concat("[", originalObject.GetType().Name, "] ");



foreach (PropertyInfo property in originalObject.GetType().GetProperties())
{
    Type comparable =
        property.PropertyType.GetInterface("System.IComparable");

    if (comparable != null)
    {
        string originalPropertyValue =
            property.GetValue(originalObject, null) as string;
        string newPropertyValue =
            property.GetValue(changedObject, null) as string;

        if (originalPropertyValue != newPropertyValue)
        {
            list.Add(string.Concat(className, property.Name,
                " changed from '", originalPropertyValue,
                "' to '", newPropertyValue, "'"));
        }
    }
}

return list;




}

}

I'm looking for System.IComparable because "All numeric types (such as Int32 and Double) implement IComparable, as do String, Char, and DateTime." This seemed the best way to find any property that's not a custom class.

Tapping into the PropertyChanged event that's generated by the WCF or web service proxy code sounded good but doesn't give me enough info for my audit logs (old and new values).

Looking for input as to if there is a better way to do this, thanks!

@Aaronaught, here is some example code that is generating a positive match based on doing object.Equals:

Address address1 = new Address();
address1.StateProvince = new StateProvince();




Address address2 = new Address();
address2.StateProvince = new StateProvince();




IList list = Utility.GenerateAuditLogMessages

(address1, address2);
(address1, address2);

> "[Address] StateProvince changed from > 'MyAccountService.StateProvince' to > 'MyAccountService.StateProvince'"

It's two different instances of the StateProvince class, but the values of the properties are the same (all null in this case). We're not overriding the equals method.

C# Solutions


Solution 1 - C#

IComparable is for ordering comparisons. Either use IEquatable instead, or just use the static System.Object.Equals method. The latter has the benefit of also working if the object is not a primitive type but still defines its own equality comparison by overriding Equals.

object originalValue = property.GetValue(originalObject, null);
object newValue = property.GetValue(changedObject, null);
if (!object.Equals(originalValue, newValue))
{
    string originalText = (originalValue != null) ?
        originalValue.ToString() : "[NULL]";
    string newText = (newText != null) ?
        newValue.ToString() : "[NULL]";
    // etc.
}

This obviously isn't perfect, but if you're only doing it with classes that you control, then you can make sure it always works for your particular needs.

There are other methods to compare objects (such as checksums, serialization, etc.) but this is probably the most reliable if the classes don't consistently implement IPropertyChanged and you want to actually know the differences.


Update for new example code:

Address address1 = new Address();
address1.StateProvince = new StateProvince();

Address address2 = new Address();
address2.StateProvince = new StateProvince();

IList list = Utility.GenerateAuditLogMessages(address1, address2);

The reason that using object.Equals in your audit method results in a "hit" is because the instances are actually not equal!

Sure, the StateProvince may be empty in both cases, but address1 and address2 still have non-null values for the StateProvince property and each instance is different. Therefore, address1 and address2 have different properties.

Let's flip this around, take this code as an example:

Address address1 = new Address("35 Elm St");
address1.StateProvince = new StateProvince("TX");

Address address2 = new Address("35 Elm St");
address2.StateProvince = new StateProvince("AZ");

Should these be considered equal? Well, they will be, using your method, because StateProvince does not implement IComparable. That's the only reason why your method reported that the two objects were the same in the original case. Since the StateProvince class does not implement IComparable, the tracker just skips that property entirely. But these two addresses are clearly not equal!

This is why I originally suggested using object.Equals, because then you can override it in the StateProvince method to get better results:

public class StateProvince
{
    public string Code { get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        StateProvince sp = obj as StateProvince;
        if (object.ReferenceEquals(sp, null))
            return false;

        return (sp.Code == Code);
    }

    public bool Equals(StateProvince sp)
    {
        if (object.ReferenceEquals(sp, null))
            return false;

        return (sp.Code == Code);
    }

    public override int GetHashCode()
    {
        return Code.GetHashCode();
    }

    public override string ToString()
    {
        return string.Format("Code: [{0}]", Code);
    }
}

Once you've done this, the object.Equals code will work perfectly. Instead of naïvely checking whether or not address1 and address2 literally have the same StateProvince reference, it will actually check for semantic equality.


The other way around this is to extend the tracking code to actually descend into sub-objects. In other words, for each property, check the Type.IsClass and optionally the Type.IsInterface property, and if true, then recursively invoke the change-tracking method on the property itself, prefixing any audit results returned recursively with the property name. So you'd end up with a change for StateProvinceCode.

I use the above approach sometimes too, but it's easier to just override Equals on the objects for which you want to compare semantic equality (i.e. audit) and provide an appropriate ToString override that makes it clear what changed. It doesn't scale for deep nesting but I think it's unusual to want to audit that way.

The last trick is to define your own interface, say IAuditable<T>, which takes a second instance of the same type as a parameter and actually returns a list (or enumerable) of all of the differences. It's similar to our overridden object.Equals method above but gives back more information. This is useful for when the object graph is really complicated and you know you can't rely on Reflection or Equals. You can combine this with the above approach; really all you have to do is substitute IComparable for your IAuditable and invoke the Audit method if it implements that interface.

Solution 2 - C#

This project on github checks nearly any type of property and can be customized as you need.

Solution 3 - C#

You might want to look at Microsoft's Testapi It has an object comparison api that does deep comparisons. It might be overkill for you but it could be worth a look.

var comparer = new ObjectComparer(new PublicPropertyObjectGraphFactory());
IEnumerable<ObjectComparisonMismatch> mismatches;
bool result = comparer.Compare(left, right, out mismatches);

foreach (var mismatch in mismatches)
{
    Console.Out.WriteLine("\t'{0}' = '{1}' and '{2}'='{3}' do not match. '{4}'",
        mismatch.LeftObjectNode.Name, mismatch.LeftObjectNode.ObjectValue,
        mismatch.RightObjectNode.Name, mismatch.RightObjectNode.ObjectValue,
        mismatch.MismatchType);
}

Solution 4 - C#

Here a short LINQ version that extends object and returns a list of properties that are not equal:

usage: object.DetailedCompare(objectToCompare);

public static class ObjectExtensions
{
    public static List<Variance> DetailedCompare<T>(this T val1, T val2)
    {
        var propertyInfo = val1.GetType().GetProperties();
        return propertyInfo.Select(f => new Variance
            {
                Property = f.Name,
                ValueA = f.GetValue(val1),
                ValueB = f.GetValue(val2)
            })
            .Where(v => !v.ValueA.Equals(v.ValueB))
            .ToList();
    }

    public class Variance
    {
        public string Property { get; set; }
        public object ValueA { get; set; }
        public object ValueB { get; set; }
    }    
}

Solution 5 - C#

You never want to implement GetHashCode on mutable properties (properties that could be changed by someone) - i.e. non-private setters.

Imagine this scenario:

  1. you put an instance of your object in a collection which uses GetHashCode() "under the covers" or directly (Hashtable).
  2. Then someone changes the value of the field/property that you've used in your GetHashCode() implementation.

Guess what... your object is permanently lost in the collection since the collection uses GetHashCode() to find it! You've effectively changed the hashcode value from what was originally placed in the collection. Probably not what you wanted.

Solution 6 - C#

Liviu Trifoi solution: Using CompareNETObjects library. GitHub - NuGet package - Tutorial.

Solution 7 - C#

I think this method is quite neat, it avoids repetition or adding anything to classes. What more are you looking for?

The only alternative would be to generate a state dictionary for the old and new objects, and write a comparison for them. The code for generating the state dictionary could reuse any serialisation you have for storing this data in the database.

Solution 8 - C#

The my way of Expression tree compile version. It should faster than PropertyInfo.GetValue.

static class ObjDiffCollector<T>
{
    private delegate DiffEntry DiffDelegate(T x, T y);

    private static readonly IReadOnlyDictionary<string, DiffDelegate> DicDiffDels;

    private static PropertyInfo PropertyOf<TClass, TProperty>(Expression<Func<TClass, TProperty>> selector)
        => (PropertyInfo)((MemberExpression)selector.Body).Member;

    static ObjDiffCollector()
    {
        var expParamX = Expression.Parameter(typeof(T), "x");
        var expParamY = Expression.Parameter(typeof(T), "y");

        var propDrName = PropertyOf((DiffEntry x) => x.Prop);
        var propDrValX = PropertyOf((DiffEntry x) => x.ValX);
        var propDrValY = PropertyOf((DiffEntry x) => x.ValY);

        var dic = new Dictionary<string, DiffDelegate>();

        var props = typeof(T).GetProperties();
        foreach (var info in props)
        {
            var expValX = Expression.MakeMemberAccess(expParamX, info);
            var expValY = Expression.MakeMemberAccess(expParamY, info);

            var expEq = Expression.Equal(expValX, expValY);

            var expNewEntry = Expression.New(typeof(DiffEntry));
            var expMemberInitEntry = Expression.MemberInit(expNewEntry,
                Expression.Bind(propDrName, Expression.Constant(info.Name)),
                Expression.Bind(propDrValX, Expression.Convert(expValX, typeof(object))),
                Expression.Bind(propDrValY, Expression.Convert(expValY, typeof(object)))
            );

            var expReturn = Expression.Condition(expEq
                , Expression.Convert(Expression.Constant(null), typeof(DiffEntry))
                , expMemberInitEntry);

            var expLambda = Expression.Lambda<DiffDelegate>(expReturn, expParamX, expParamY);

            var compiled = expLambda.Compile();

            dic[info.Name] = compiled;
        }

        DicDiffDels = dic;
    }

    public static DiffEntry[] Diff(T x, T y)
    {
        var list = new List<DiffEntry>(DicDiffDels.Count);
        foreach (var pair in DicDiffDels)
        {
            var r = pair.Value(x, y);
            if (r != null) list.Add(r);
        }
        return list.ToArray();
    }
}

class DiffEntry
{
    public string Prop { get; set; }
    public object ValX { get; set; }
    public object ValY { get; set; }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPete NelsonView Question on Stackoverflow
Solution 1 - C#AaronaughtView Answer on Stackoverflow
Solution 2 - C#bkaidView Answer on Stackoverflow
Solution 3 - C#Mike TwoView Answer on Stackoverflow
Solution 4 - C#RickView Answer on Stackoverflow
Solution 5 - C#Dave BlackView Answer on Stackoverflow
Solution 6 - C#ali-myousefiView Answer on Stackoverflow
Solution 7 - C#Phil HView Answer on Stackoverflow
Solution 8 - C#IlPADlIView Answer on Stackoverflow