Hashing the state of a complex object in .NET

Posted by Jan on Stack Overflow See other posts from Stack Overflow or by Jan
Published on 2010-03-26T22:29:28Z Indexed on 2010/03/26 22:33 UTC
Read the original article Hit count: 270

Filed under:
|
|

Some background information:

I am working on a C#/WPF application, which basically is about creating, editing, saving and loading some data model.

The data model contains of a hierarchy of various objects. There is a "root" object of class A, which has a list of objects of class B, which each has a list of objects of class C, etc. Around 30 classes involved in total.

Now my problem is that I want to prompt the user with the usual "you have unsaved changes, save?" dialog, if he tries to exit the program. But how do I know if the data in current loaded model is actually changed?

There is of course ways to solve this, like e.g. reloading the model from file and compare against the one in memory value by value or make every UI control set a flag indicating the model has been changed. Now instead, I want to create a hash value based on the model state on load and generate a new value when the user tries to exit, and compare those two.

Now the question:

So inspired of that, I was wondering if there exist some way to generate a hash value from the (value)state of some arbitrary complex object? Preferably in a generic way, e.g. no need to apply attributes to each involved class/field.

One idea could be to use some of .NET's serialization functionality (assuming it will work out-of-the-box in this case) and apply a hash function to the content of the resulting file. However, I guess there exist some more suitable approach.

Thanks in advance.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about c#