Overriding Equals()

  • Thread starter Thread starter David Hoffer
  • Start date Start date
D

David Hoffer

Why is it that when I override Equals I get the following warning? What am I
suppose to do?

warning CS0659: 'XXX.MyObject' overrides Object.Equals(object o) but does
not override Object.GetHashCode()
 
David Hoffer said:
Why is it that when I override Equals I get the following warning? What am I
suppose to do?

warning CS0659: 'XXX.MyObject' overrides Object.Equals(object o) but does
not override Object.GetHashCode()

If you override Equals but not GetHashCode, your objects won't behave
well if used as keys in a Hashtable. See the docs for Object.Equals for
more information.
 
David,

Think of a hashcode as a quick way of uniquely identifying similar
instances of a type. It is recommended that when you override Equals (which
is used for comparisons) that you override GetHashCode to produce the same
result for two instances that will return true. The reason for this is that
the hashcode is used for comparisons as well (for things like Hashtables).

Hope this helps.
 
David Hoffer said:
I didn't see anything in the docs on this....

Open the docs for Object.Equals, then click on the instance method
rather than the static method. Under the list of bullet points, it has:
"See GetHashCode for additional required behaviors pertaining to the
Equals method." It also has (a few lines later): "Types that override
Equals must also override GetHashCode; otherwise, Hashtable might not
work correctly."
 
Back
Top