Carbine
Carbine

Reputation: 7903

Which methods internally call GetHashCode?

I am aware of the importance to override GetHashCode when we override Equals method. I assume Equals internally calls GetHashCode.

What are the other methods that might be internally using GetHashCode?

Upvotes: 1

Views: 734

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1064114

I assume Equals internally calls GetHashCode.

That would be pretty unusual actually. GetHashCode is used mainly by dictionaries and other hash-set based implementations; so: Hashtable, Dictionary<,>, HashSet<>, and a range of other things. Basically, GetHashCode serves two purposes:

  • getting a number which loosely represents the value, and which can be used, for example, for distributing a set of keys over a range of buckets via modulo, or any other numeric categorisation
  • proving non-equality (but never proving equality)

See also: Why is it important to override GetHashCode when Equals method is overridden?

Upvotes: 4

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

Equals doesn't internally call GetHashCode.
GetHashCode is used by many classes as a means to improve performance: If the hash codes of two instances differ, the instances are not equal by definition so the call to Equals can be skipped.
Only if the hash codes are the same it needs to call Equals, because multiple instances can have the same hash code, even if they are different.

Concrete examples of classes that work like this:

Upvotes: 4

Related Questions