I want to be able to compare objects by the hashcode.
Per example, one is the object itself, and the other is serialized (binary) and then recovered version of the object.
How can I save the hash in the serialized (binary) object?
Why would you have to serialize the hash code? Instead you should provide a proper implementation of GetHashCode()
and Equals()
in your object that allows you to compare two objects based on their values - if two objects are equal their hash codes have to match. So once you have deserialized the object, you can use GetHashCode()
on it and compare it with the other object. Note that the fact that two hash codes match is not enough to determine equality, they might still be different - you will have to call a proper implementation of Equals()
to determine equality.
If you just want to compare custom fields within an object and a full comparison might be too expensive (i.e. a large binary array) it might make sense to generate an MD5 hash (i.e. with MD5CryptoServiceProvider.ComputeHash()
) on the field and store that within the object itself, it will then be serialized just like any other object property.