I have two complex objects of the same type. I want to check if there is any difference between the two of these objects. I have two options of achieving this, either by converting both of these objects to string using JsonConvert.SerializeObject and compare the string like
var existingData = JsonConvert.SerializeObject(objOld);
var newData = JsonConvert.SerializeObject(objNew);
return existingData == newData;
The other option is to use the reflection and loop through all the properties like below.
protected bool MatchObject(object newObj, object oldObj)
{
Type currentType = newObj.GetType();
PropertyInfo[] props = currentType.GetProperties();
bool isSameObject = true;
foreach (var prop in props)
{
var i = prop.GetValue(newObj);
var f = prop.GetValue(oldObj);
if (!object.Equals(i, f))
{
isSameObject = false;
break;
}
}
return isSameObject;
}
Which of the above approach is more efficient as per the performance perspective?
CodePudding user response:
Ugh. Faced between "serialize it to string and use string compare" and "use reflection" I think I'd tick the "none of the above" box
Have you considered using a record
instead of a class
? The compiler writes all the necessary code for you, to determine equality of a record based on the values of its properties, so all that is left for you to do is test your record instances for equality
CodePudding user response:
Alternative ready-to-use option is assertion frameworks. For example 'FluentAssertions' can compare object graph
newObject.Should().BeEquivalentTo(oldObject);
Line above will throw an exception if object and their properties aren't equal.
Object graph comparison
Notice that this is just another library available via NuGet, so you can use in the "production" code as well ;)