ValeraT1982 / ObjectsComparer

C# Framework provides mechanism to compare complex objects, allows to override comparison rules for specific properties and types.
MIT License
352 stars 86 forks source link

Members of type object are not taken into account #48

Closed BAV0 closed 1 year ago

BAV0 commented 1 year ago

Issue: When comparing 2 objects of the same class, which has a member of type object, this member's value (or type for that matter) is not taken into account.

Example: (.NET Fiddle)

public class Model {
    public object Prop1 { get; set; }
}

var o1 = new Model { Prop1 = "string" };
var o2 = new Model { Prop1 = "other string" };

var comparer = new ObjectsComparer.Comparer<Model>();
var result = comparer.Compare(o1, o2, out var _);

Console.WriteLine(result); // Should be false

Workaround: (.NET Fiddle) A possible workaround is to override the comparison for object-type members:

comparer.AddComparerOverride<object>(new ObjectValueComparer());

public class ObjectValueComparer : IValueComparer
    {
        public bool Compare(object o1, object o2, ComparisonSettings settings)
        {
            if (o1.GetType() != o2.GetType())
            {
                return false;
            }

            return new Comparer().Compare(o1.GetType(), o1, o2);
        }

        public string ToString(object value)
        {
            return value.ToString();
        }
    }
ValeraT1982 commented 1 year ago

It'a an expected behavior. Comparer "looks" at the type of the property to get the list of the members.

More details here