First let me repeat what I said in my comment.
The logic is : If a.GetHashcode() != b.GetHashCode()
then a != b,
If a.GetHashCode() == b.GetHashCode() && a.Equals(b)
then a == b
, All GetHashcode()
does for you is lets you skip the Equals()
check if you have two different values. That is why you need to implement both, If you only implement Equals()
then the a.GetHashCode() == b.GetHashCode()
step fails and it never tries the Equals() you implemented.
GetHashCode()
should be fast and it's value should not change while it sits in a collection that depends on it's value. So don't modify VisitKey
nor Time
if you are storing these inside a Dictionary
or HashSet
or similar.
So all you need to do is:
public override int GetHashCode()
{
var visitKeyHash = this.VisitKey == null ?
251 : this.VisitKey.GetHashCode();
var timeHash = this.Time.Year + this.Time.Month + this.Time.Day +
this.Time.Hour + this.Time.Minute;
return ((visitKeyHash * 251) + timeHash);
}
public override bool Equals(object obj)
{
//Two quick tests before we start doing all the math.
if(Object.ReferenceEquals(this, obj))
return true;
KnownMessage message = obj as KnownMessage;
if(Object.ReferenceEquals(message, null)))
return false;
return this.VisitKey.Equals(message.VisitKey) &&
this.time.Year.Equals(message.Time.Year) &&
this.time.Month.Equals(message.Time.Month) &&
this.time.Day.Equals(message.Time.Day) &&
this.time.Hour.Equals(message.Time.Hour) &&
this.time.Minute.Equals(message.Time.Minute);
}