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

- 228,013
- 71
- 433
- 510

- 4,233
- 12
- 42
- 55
4 Answers
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>
).

- 1,421,763
- 867
- 9,128
- 9,194
-
Impeccable explanation Jon .Great. – user160677 Sep 03 '09 at 20:49
-
HashCode is generated by the System ? like random number will it return random value ? – user160677 Sep 03 '09 at 21:00
-
3The 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 – R. Martinho Fernandes Sep 03 '09 at 21:10
-
Thank you for clearing my doubt.Thank you very much ,once again. :) – user160677 Sep 03 '09 at 21:12
No, a HashCode is not guaranteed to be unique. But you already have references to your objects, they are perfect for tracking identity, using object.ReferenceEquals()
.

- 228,013
- 71
- 433
- 510

- 263,252
- 30
- 330
- 514
-
1+1 Even though your wording is a little unclear your point is still there. – ChaosPandion Sep 03 '09 at 20:43
-
1I think you should point that since `==` can be overloaded, so the correct way to test referential equality is the `object.ReferenceEquals()` method. – R. Martinho Fernandes Sep 03 '09 at 20:52
-
-
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.

- 8,530
- 6
- 43
- 64
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).

- 142,018
- 20
- 234
- 287