I was wondering how I would find the difference between two objects of the same class. So if I had a Person class with the only difference being Age it will return the field/fields that are different.
Thanks
I was wondering how I would find the difference between two objects of the same class. So if I had a Person class with the only difference being Age it will return the field/fields that are different.
Thanks
It really depends on how deep you want to go in comparing the entities, but the idea with reflection is the best one here. The code would be something like that:
If you need to deeply process nested objects, then, as it was said before, you will need some hash table that will remember already processed objects and prevent them from being processed again. Hope this helps!
I used Michael Hoffmann's answer, however I found it lacking support if one of the properties is null, and if one throws an error (usually found when comparing "Type" objects), or if one is a collection.
while there is still work to be done, I am posting here the base modified code:
You will need to recursively go through all private and public properties and fields on the entire object graph. Use a HashSet to keep track of objects you have already checked so you don't return duplicate results or get into a stack overflow.
If the property type is IComparable, you can cast the values of that property to IComparable and use IComparable.CompareTo. If not, you'll have to recursively call the your differential method on the sub-objects.
What about something like this
This gets you a list of the property names that are different between the two objects. I don't think this is all the way to the solution you are looking for but I think it is a decent start
In my example this would return "Prop2" as that is the property whose values differ betwen the objects.
EDIT: Of course this assumes any complex types in your object implement equality comparisons that do what you expect. If not you would need to dive down the object graph and do nested compares as others have suggested
Here's some simple code I use for just such a thing while debugging:
To use it, your code might look something like this:
This isn't something that C# (or .NET really) supports directly, however you could implement something by hand for specific types, or write code that uses reflection to diff arbitrary objects.
If you choose the later, you will have to decide how deep you want to go into the object graph to identify whether two instances are identical or not and how you will compare certain primitive types for equality (doubles, for instance).
Writing a reflection-based differencing algorithm is more difficult that it seems at first - personally, I would implement this functionality directly for the types (or within a helper class) where you need it.