views:

328

answers:

4

What is the use of GetHashCode()? Can I trace object identity using GetHashCode()? If so, could you provide an example?

A: 

Read this article, about using GetHasCode to identify objects (which you should not do)

article

Colin
+1  A: 

The value itself is used in hashing algorithms, such as hashtables.

In its default implementation, GetHasCode does not guarantee the uniqueness of an object, thus for .NET objects should not be used as such,

In you own classes, it is generally good practice to override GetHashCode to create a unique value for your object.

Jaimal Chohan
+1  A: 

It's used for algorithms\data structures that require hashing (such as a hash table). A hash code cannot on its own be used to track object identity since two objects with the same hash are not necessarily equal. However, two equal objects should have the same hash code (which is why C# emits a warning if you override one without overriding the other).

Lee
+17  A: 

Hash codes aren't about identity, they're about equality. In fact, you could say they're about non-equality:

  • If two objects have the same hash code, they may be equal
  • If two objects have different hash codes, they're not equal

Hash codes are not unique, nor do they guarantee equality (two objects may have the same hash but still be unequal).

As for their uses: they're almost always used to quickly select possibly equal objects to then test for actual equality, usually in a key/value map (e.g. Dictionary<TKey, TValue>) or a set (e.g. HashSet<T>).

Jon Skeet
Impeccable explanation Jon .Great.
HashCode is generated by the System ? like random number will it return random value ?
The default `GetHashCode` implementation returns some sort of internal object identifier used by the runtime. But since `GetHashCode` is virtual you can override it to return whatever you feel like. Check these two questions when you need to override it: http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode and http://stackoverflow.com/questions/873654/overriding-gethashcode-for-mutable-objects-c
Martinho Fernandes
Thank you for clearing my doubt.Thank you very much ,once again. :)