Deep Comparing Objects in C#

Shivam Singh
2 min readDec 16, 2020

Basic implementation walk through for comparing two C#/NET Objects.

Deep comparing two objects has always been a convoluted process.

Often we are presented with a situation where we may have to compare two objects in our program. It can be either to create an audit log or to avoid users to enter duplicate data.

This process of object comparison in C#/.NET is being simplified by the Nuget package Compare-Net-Objects offered by the Kellerman Software group. Compare-Net-Objects uses reflection to perform the comparisons.

Let’s jump into our implementation example implementation for more details.

Step 1:
Make sure you’ve downloaded the correct Nuget Package.

Step 2:

Creating two Person Objects for comparison.

Step 3:

By default Compare-Net Objects only distinguishes the first difference. Hence to capture all the differences of our object, we have to set the MaxDifferences property of our ComparisonConfig class to the total number of attributes. ComparisonConfig is part of the CompareLogic class.

Step 4:

Now that we’ve setup our CompareLogic, we can call the Compare method and pass our two objects(person1, person2) created in the step 1.

This returns a list of differences.

Performing Quick Watch on differences variable.

As we can see we have caught two differences on our objects(person1, person 2). Also you can note, the values of attributes are stored as string in Object1Value and Object2Value irrespective of their original type.

Step 5:

We can loop through these differences and either save or display it. I’ll print the values for example.

Compare-Net-Objects also provides the functionality of comparing lists, dictionaries. In conclusion we can safely say that, Compare-Net-Objects is a very powerful tool which has considerably eased down the process of performing deep comparisons and has made the life of .NET developers considerably easy!

--

--

Shivam Singh
0 Followers

Enthusiastic about Programming and Sports