Override Equals ... AND Hashcode?

M

Mark

I've built a class and overroad the Equals method. I've gotten the warning
below. I'm unfamiliar with the "GetHashCode" method. An explantion of the
method and its relation to the warning would be appreciated.

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

Thanks in advance.

Mark
 
J

Jon Skeet [C# MVP]

Mark said:
I've built a class and overroad the Equals method. I've gotten the warning
below. I'm unfamiliar with the "GetHashCode" method. An explantion of the
method and its relation to the warning would be appreciated.

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

Basically, if you override Equals but don't override GetHashCode, your
object may not work properly when put into a HashTable. See the docs on
GetHashCode for details of it.

Personally I'd suggest ignoring the requirement to make the hash code
constant after construction - if the object is mutable and changes in a
way which affects equality, it makes sense for the hash code to change
too. However, that does mean that a hash table may not be able to look
up the object using even the same reference if you change the contents
of the object after putting it into the hashtable.
 
G

Guest

I'm unfamiliar with the "GetHashCode" method.

GetHashCode is used by hash tables (like System.Collections.Hashtable) to
decide where to put your data when you insert it into the table.

It is also used to make a "first cut" at doing a lookup; that is, the hash
table uses GetHashCode to help it find your data in the table. It uses
GetHashCode to eliminate most of the entries without looking at them. Then it
uses the Equals method to search through those that are left. Thus,
GetHashCode and Equals are related and the compiler reminds you to please
override both if you override either.

One final note about System.Collections.Hashtable: it stores <key,value>
pairs. When you insert, the table calls GetHashCode on the key to help it
decide where to store your data in the table. When you lookup, it calls
GetHashCode and Equals on the key. If you use your objects as the key in
Hashtable, then lookups can fail if GetHashCode and Equals don't work
together (e.g. Equals objects must return the same thing from GetHashCode).

This is a pretty big/confusing topic - hope that gets you started.

Mark
 

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