Archive for the ‘unit-testing’ Category

Comparing object properties in C#

leave a comment »

I needed today, in my unit tests, a way to compare two objects of the same type, property by property.
In addition to this I needed the following:

    -If the property is a reference type, then go inside it and compare that too, property by property. (Basically deep object property comparison).
    -If the property is IEnumerable, then compare properties of each element inside the IEnumerable.
    -If the elements inside the IEnumerable are themselves IEnumerable then this could go on many levels deep, but this was not on my requirements.
    -I also want the possibility to ignore certain properties in the comparison, such as property which is a delegate (like the Filter property of the PagedCollectionView framework class).
    And of course I would need to know which properties were not equal, so I could show into my assertions.

Obviously this involves some heavy reflection code which I’m sure it would be fun to write if you had the time.
An alternative is to use a free library, with just one class, that does exactly this: http://comparenetobjects.codeplex.com/
Usage is very simple, and supports all kind of useful features which you can see below:

var compareObjects = new CompareObjects()
                CompareChildren = true, //this turns deep compare one, otherwise it's shallow
                CompareFields = false,
                CompareReadOnly = true,
                ComparePrivateFields = false,
                ComparePrivateProperties = false,
                CompareProperties = true,
                MaxDifferences = 1,
                ElementsToIgnore = new List<string>() { "Filter" }
            bool areEqual = compareObjects.Compare(objectA, objectB);
            Assert.IsTrue(areEqual, compareObjects.DifferencesString); //DifferencesString contains exactly what property and what value(s) was different

For Silverlight you do have to remove a couple of line of codes from it, related to DataTable comparison, which don’t exist in silverlight, but it’s easy and only takes a couple of minutes.

Happy Deep Object Comparisons :)


Written by Liviu Trifoi

April 28, 2011 at 6:20 pm