Overwriting Equal() and get-hash funct. for HashTable

Started by
2 comments, last by cdoubleplusgood 10 years, 7 months ago

So the MSDN for HashTables says:

The objects used as keys by a Hashtable are required to override the Object.GetHashCode method (or the IHashCodeProviderinterface) and the Object.Equals method (or the IComparer interface).

However, is that really necessary for elemental data types? The example further down that page doesn't show any kind of overwriting for the string key.

Here is my technical background info.
Advertisement

Well it is necessary, but it's already done for you. All the basic types already have perfectly usable implementations of GetHashCode().

... and if you have to roll your own, I've always found the general algorithm proposed in Advanced Java. It is illustrated in this article about Java's object.hashCode().


However, is that really necessary for elemental data types? The example further down that page doesn't show any kind of overwriting for the string key.

When you write your own value types (struct), and use them as keys, you should (really!) implement Equals and GetHashCode because the default implementation is more or less useless.

This topic is closed to new replies.

Advertisement