I was attempting to use the GetHashCode() value to determine if an object has changed after it's been validated via ajax calls in an ASP.NET MVC application. However, I noticed that this did not work because the hash code value when returned during validation would be different than the hash code generated when the object was created again from the model binding with the same values in another request after the validation request. I was able to solve this problem by creating a SHA hash instead, but I'm curious on why I was seeing this behavior.
I know that hash codes generated from GetHashCode() should not be persisted and can differ on different platforms and over time. I thought that the time period was short enough when I first came up with this idea since these two calls were made in milliseconds of each other and when debugging I confirmed that the model contained the exact same values, but still produced a different hash code.
I'm curious about why this behavior is exhibited. Why would this happen even though this is a single run of the application, albeit a web application? Does this have to do with the ASP.NET life cycle?
In case needed here's the class & GetHashCode implementation I was using:
class DispositionSubmission
{
[Display(Name = "Client")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Client is required.")]
public string ClientId { get; set; }
public string Carrier { get; set; }
public Dictionary<string, string> DispositionInfo { get; set; }
public DispositionType Type { get; set; } //int based enum
...
public override int GetHashCode()
{
unchecked
{
int hash = (int)15485863;
int bigPrime = (int)15485867;
hash = hash * bigPrime ^ ClientId.GetHashCode();
hash = hash * bigPrime ^ (Carrier ?? "").GetHashCode();
hash = hash * bigPrime ^ DispositionInfo.GetHashCode();
hash = hash * bigPrime ^ Type.GetHashCode();
return hash;
}
}
}