Comparing Objects and getting more info on the differences

September 26, 2015 - .NET, C#

Comparing Objects

C# has a number of useful comparison interfaces that we can use and implement, so this would seem to be a redundant post, wouldn’t it. We can use IComparable, IComparable, or even the .Equals() method and compare two objects relatively sufficiently.

However, in the context of something like a Unit Test, if we want to compare/assert that two objects are equal, we would ideally be able to output what is different between them- if we have two objects with many properties and merely compare them, then the developer will haveto debug to figure out which properties actually were different between them, whereas we pretty much have access to that information in the Unit Test. At the same time, we don’t want to have to write sophisticated comparison routines for every object type. Instead, it might be reasonable to try a more generic approach. If we want to compare two instances of objects we could merely compare their public, readable properties. While this won’t get everything, it means we can store the actual differences which can be expressed as part of debugging output or the output of a unit test.

An Array of issues

The major issue I encountered was handling of Arrays. I previously wrote about the task of serializing Arrays. The tricky part of dealing with Arrays is the same here, which is how we manage the Rank. another issue in this situation is how do we compare Arrays in a meaningful way if they have different ranks or dimensions? I cannot really think of a good way to do so so What I’ve done is merely ignore when the objects passed in are arrays. This means that, technically, the solution is wrong (since the arrays between two instances of an object may differ) but since I’m actually going to be using this code in a Unit Test consideration and would rather not spend dozens of hours merely working on a way to compare objects I think it will work to get started.

Effectively, we can use reflection to grab each property, then compare the values of the two properties in the two instances being compared. If they are different we can add the property to a list of Strings to return, indicating the properties that differ; otherwise, we don’t. Once returned, we can use another helper function to use the list to construct a more useful set of the differences between the two elements.

With this, we can now use a test program to show off the results:

Which outputs the following:

Have something to say about this post? Comment!