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

Getting each property as added or deleted when comparing against a null object #36

Closed PeterOsterdahl closed 2 years ago

PeterOsterdahl commented 2 years ago

Hi Valera! I'm wondering what the best way would be to change the behaviour when one of the compared objects is null and the other isn't. In the default implementation one value would be '' and the other object.ToString(). The result I'm looking for is to have each property of the not null object returned as added or deleted (depending on if they are from obj1 or obj2). Is this possible?

Great work by the way! //Peter

ValeraT1982 commented 2 years ago

Don't think it's possible. Can you please give an example of the objects and comparison result you want?

PeterOsterdahl commented 2 years ago

It's rather simple class A{ public string Name {get;set;} } class B { public int Id {get; set;} public A InnerA {get;set;} }

var B1 = new B{ Id = 1, InnerA = new A{Name = "a"}}; var B2 = new B{ Id = 1};

Comparing should yield something like : Difference: DifferenceType=MissedElementInSecondObject, MemberPath='InnerA.Name', Value1='a', Value2=''

ValeraT1982 commented 2 years ago

You can loop through differences and change '' to added or deleted.

PeterOsterdahl commented 2 years ago

I think the default behaviour of the Comparer when one object is null is to return new Difference(string.Empty, DefaultValueComparer.ToString(obj1), DefaultValueComparer.ToString(obj2)); so the output will be Difference: DifferenceType=ValueMismatch, MemberPath='InnerA', Value1='ObjectsComparer.Examples.Example6.Example6Tests+A', Value2=''. So there is really nothing to iterate. I solved this by creating my own Comparer now but I wondered if there was something more elegant that could be done

ValeraT1982 commented 2 years ago

I don't see any elegant solution for your case.