Overriding Equals()

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()
 
J

Jon Skeet [C# MVP]

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.
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
J

Jon Skeet [C# MVP]

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."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top