1

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?

ali_m
  • 71,714
  • 23
  • 223
  • 298
Carbine
  • 7,849
  • 4
  • 30
  • 54
  • Implementations of `Equals()` don't normally call `GetHashCode()`, but any hashing container will call it for the elements of its collection. – Matthew Watson Aug 21 '13 at 10:53
  • Eric Lippert wrote a nice blog about it: http://blogs.msdn.com/b/ericlippert/archive/2011/02/28/guidelines-and-rules-for-gethashcode.aspx – Wouter de Kort Aug 21 '13 at 10:58
  • My apologies, when I call a Overriden `Equals` method. `GetHashCode`is internally called without explicit mention in the Overriden `Equals` method. Hence wanted to know what all cases triggers the call of 'GetHashCode' – Carbine Aug 21 '13 at 11:01
  • This is a question you should never ask. What other code runs in a program that *might* use it is unknowable. – Hans Passant Aug 21 '13 at 12:53
  • If we override `GetHashCode` wont it be good to know where all it will used? From Brian's comment below it might will be used extensively in LINQ queries... I was expecting such answer :) – Carbine Aug 21 '13 at 16:02
  • 1
    Step 1: Download the .NET BCL source code, available on the Microsoft website, and string-search for GetHashCode. Step 2: . Step 3: Profit! – M.A. Hanin Sep 01 '13 at 01:26

2 Answers2

4

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:

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
4

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?

Community
  • 1
  • 1
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    As an addition to Marc's examples, it's worth noting that Linq makes frequent use of GetHashCode. – Brian Aug 21 '13 at 15:07