According to this Eric blog,
Rule: Consumers of GetHashCode cannot rely upon it being stable over time or across appdomains. Suppose you have a Customer object that has a bunch of fields like Name, Address, and so on. If you make two such objects with exactly the same data in two different processes, they do not have to return the same hash code. If you make such an object on Tuesday in one process, shut it down, and run the program again on Wednesday, the hash codes can be different. This has bitten people in the past. The documentation for System.String.GetHashCode notes specifically that two identical strings can have different hash codes in different versions of the CLR, and in fact they do. Don't store string hashes in databases and expect them tbe the same forever, because they won't be.
I am using this class,
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string ModelNumber { get; set; }
public string Sku { get; set; }
public string Description { get; set; }
public double Price { get; set; }
public double NewPrice { get; set; }
public override int GetHashCode()
{
return Id ^ (Name ?? "").GetHashCode() ^ (ModelNumber ?? "").GetHashCode() ^ (Sku ?? "").GetHashCode()^ (Description ?? "").GetHashCode() ^ Price.GetHashCode() ^ NewPrice.GetHashCode();
}
}
I am saving the hash of the product properties object in database for change tracking. Means the hash code will tell me whether the object changed or not. If a hash can be changed between app-domain then what is the other way?
I am saving the hash of the product properties object in database for change tracking.
Don't do that. That's pretty much the definition of requiring the hash code to be stable over time. AppDomains are pretty irrelevant to this, to be honest.
If you need some sort of hash which is stable, you might want to convert your object to a stable binary representation (e.g. using BinaryWriter
) and then take a SHA-256 hash of that - because SHA-256 (and similar cryptographic hashes) are designed to be stable.
See more on this question at Stackoverflow