Can I track the identity of an object using GetHashCode?

What is GetHashCode() ? Is it possible to track the identity of an object using GetHashCode() ? If so, can you give an example?

+4
source share
4 answers

Hash codes are not associated with identification; they relate to equality. In fact, you can say that they are not equal:

  • If two objects have the same hash code, they can be equal
  • If two objects have different hash codes, they are not equal

The hash codes are not unique and do not guarantee equality (two objects can have the same hash, but still be unequal).

As for their use: they are almost always used to quickly select, possibly equal objects, then to check the actual equality, usually in a key / value map (for example, Dictionary<TKey, TValue> ) or a set (for example, HashSet<T> ) .

+22
source

No, HashCode is not guaranteed to be unique. But you already have references to your objects, they are ideal for tracking identification using object.ReferenceEquals() .

+5
source

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

In its default implementation, GetHasCode does not guarantee the uniqueness of an object; therefore, .NET objects cannot be used as such.

In your own classes, it is usually recommended to override GetHashCode to create a unique value for your object.

+1
source

It is used for algorithms / data structures that require hashing (e.g. hash tables). The hash code alone cannot be used to track the identifier of an object, since two objects with the same hash are not necessarily equal. However, two identical objects must have the same hash code (therefore, C # gives a warning if you redefine one without overriding the other).

+1
source

All Articles