Comparing Two Complex Objects of the Same Class






3.47/5 (6 votes)
Comparing two objects of the same class using reflection and extension methods
Introduction
This tip shows how to compare two objects of the same class using reflection and extension methods.
Background
You have two objects of the same class (class contains sub classes, properties, sub classes contain properties, etc.) and you need to compare whether those two objects are the same or not. This technique doesn't need IEquals
, IComparable
interfaces to inherit.
Using the Code
Create a static
class with the name "CompareTwoObjects
" and add the below code to it:
public static object CompareEquals<T>(this T objectFromCompare, T objectToCompare)
{
if (objectFromCompare == null && objectToCompare == null)
return true;
else if (objectFromCompare == null && objectToCompare != null)
return false;
else if (objectFromCompare != null && objectToCompare == null)
return false;
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
object dataFromCompare =
objectFromCompare.GetType().GetProperty(prop.Name).GetValue(objectFromCompare, null);
object dataToCompare =
objectToCompare.GetType().GetProperty(prop.Name).GetValue(objectToCompare, null);
Type type =
objectFromCompare.GetType().GetProperty(prop.Name).GetValue(objectToCompare,null).GetType();
if (prop.PropertyType.IsClass &&
!prop.PropertyType.FullName.Contains("System.String"))
{
dynamic convertedFromValue = Convert.ChangeType(dataFromCompare, type);
dynamic convertedToValue = Convert.ChangeType(dataToCompare, type);
object result = CompareTwoObjects.CompareEquals(convertedFromValue, convertedToValue);
bool compareResult = (bool)result;
if (!compareResult)
return false;
}
else if (!dataFromCompare.Equals(dataToCompare))
return false;
}
return true;
}
This results in whether all the properties of the class and the subclasses contain the same value or not.
Usage:
Object1.CompareEquals(Object2);
Points of Interest
Previously, I could see that to compare two objects, we need to implement the IEquals
, IComparable
interfaces and then loop through each of the properties explicitly to make sure the values are the same or not. But my code is a generic code and this is reliable and independent as well.
History
I used extension methods concept along with reflection which made it easy to compare two objects with minimal code.