Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing objects for changes

Tags:

c#

comparison

I have an application that needs to determine whether a user has made a change to an object. So, when the object is first loaded, I create a deep copy (using serialization/deserialization) and save the copy to a separate field. The copy becomes myCurrentObject, and the original becomes myOriginalObject.

Now I need to test myCurrentObject for changes, which I plan to do by comparing it to myOriginalObject. All I need is a boolean result indicating whether any changes have been made. I have already determined that a simple hashcode comparison won't work. GetHashCode() generates different results for the two objects, even when there are no changes.

I am getting ready to write a method to do a property-by-property comparison, but before I do, I thought I would check to see if there is a simpler and more reusable way to test myCurrentObject to see if it has changed from myOriginalObject.

Any suggestions? Thanks for your help.

like image 734
David Veeneman Avatar asked Mar 26 '10 15:03

David Veeneman


2 Answers

Instead could you implement a OnPropertyChanged event on each of your properties then you could just see if the event was ever thrown. If you specifically implement INotifyPropertyChanged, you will get the added benefit that you can do WPF binding if you ever want to.

If that isn't possible, you could probably implement a solution with reflection that would traverse both objects looking for differences.

like image 160
Jake Pearson Avatar answered Sep 30 '22 16:09

Jake Pearson


What if an event is raised when a property is changed?

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx

like image 23
Raj Kaimal Avatar answered Sep 30 '22 14:09

Raj Kaimal