It is not related to garbage collection, well, no more than all other type members.
This function is used to make an object to be capable of serving as an index type in
associative collections such as
System.Collections.Generic.Dictionary
,
System.Collections.Generic.SortedDictionary
or
System.Collections.Generic.SortedList
. Such collection allow for fast finding of an object by some key of any type; and the computational complexity of such search is O(1); that is, the time of search asymptotically does not depend on the size of the collection.
The collection data structure classify data into
buckets (please see the links above) having the same value of hash code, which is the key of the search algorithm.
See also:
http://www.sgi.com/tech/stl/HashedAssociativeContainer.html[
^],
http://en.wikipedia.org/wiki/Hash_table[
^],
http://en.wikipedia.org/wiki/Big_O_notation[
^].
Whenever you define a type and override
equality method
System.Object.Equals
, you also need to override
System.Object.GetHashCode
. Please see:
http://msdn.microsoft.com/en-us/library/system.object.aspx[
^].
This is quite natural: you cannot consistently implement one without another preserving correct behavior of the type as a collection key.
[EDIT]
Logically equal objects should manifest equal hash code values, and unequal objects should return values of the hash code which are different with high probability — this is the major requirement for the class implementation.
You might be puzzled to know how should you implement hash code for your classes when it is required. I'll give you a very simple recipe. Consider your class has several fields which are use in equals implementation. Supposing they already have implementation of hash code, take all their hash code values and make a binary XOR of all of them. Return the resulting value as a hash code of the composing object. That's it.
For a home exercise, think why this implementation works. :-)
—SA