Is there a method that compares to objects of the same type and determines rough equivalence (by comparing the values of public properties exposed)? Kind of similar to how automapping utils work?
Ideally we would have a method like this:
public static bool IsEquivalentTo<T>(this T source, T target);
We already have EquivalentTo extension method but that’s only for comparing whether different IEnumerables and Dictionaries hold the same elements. You should be able to get what you want by converting each model to an object dictionary and comparing them with EquivalentTo, e.g:
var hasSameProperties = from.ToObjectDictionary().EquivalentTo(to.ToObjectDictionary());
In following with NUnit’s conventions, I only use EquivalentTo for comparing collections - so I’d call the extension method something else, maybe HasPropertiesEqual() or leave it without wrapping in another extension method so it’s clear how they’re equal.
You don’t need the extra checks since ToObjectDictionary() returns null (like most extension methods) and EquivalentTo() already does the null check dance:
Thanks, on deeper investigation, it looks like ToObjectDictionary() does not build KV pairs for nested properties (of top level properties), so comparing anything but top level properties is not going to work with ‘ToObjectDictionary’. What a shame. Would be nice if it could build the KV pairs right down the object hierarchy. Perhaps an overloaded method?