IsEquivalentTo()?

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());

So we are thinking something like this:

        public static bool IsEquivalentTo<T>(this T source, T target)
        {
            if (source == null && target == null)
            {
                return true;
            }

            if (source == null || target == null)
            {
                return false;
            }

            return source.ToObjectDictionary().EquivalentTo(target.ToObjectDictionary());
        }

Does that do it, or are there some other edge cases to worry about? I am not familiar with ToObjectDictionary() or EquivalentTo()

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:

if (thisList == null || otherList == null)
    return thisList == otherList;

ToObjectDictionary() just converts a POCO into a Dictionary<string,object> making it easy to dynamically inspect its property values.

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?