0

Dictionary in C# uses GetHashCode() to retrieve hash code of a given key. I walk through whole of the Dictionary Class, but there is not any definition for GetHashCode() function. It is bothering me and I don't know how I can find definition of it in this class!

Assume I am using Dictionary<int,int> a = new Dictionary<int,int>(), now what is the hash code of a given key in this structure? (e.g. suppose this: a.Add(123,43). what is the hash code of this key, if number of buckets being 50)

This is a part of Insert() function of Dictionary class.

private void Insert(TKey key, TValue value, bool add)
    {
        int freeList;
        if (key == null)
        {
            ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
        }
        if (this.buckets == null)
        {
            this.Initialize(0);
        }
        int num = this.comparer.GetHashCode(key) & 0x7fffffff;
        int index = num % this.buckets.Length;
Chavoosh
  • 425
  • 4
  • 15
  • What do you mean "hash code of a given key"? – Ant P Dec 28 '13 at 17:09
  • 3
    Do you mean this? http://stackoverflow.com/questions/3893782/how-is-gethashcode-implemented-for-int32 – Ant P Dec 28 '13 at 17:09
  • I want know the algorithm that used for generating hash code of a given key. Now I am asking if that key is an integer, how it will calculate? – Chavoosh Dec 28 '13 at 17:10
  • Then it'll be the hash code of the integer. – Ant P Dec 28 '13 at 17:11
  • 1
    As usual, _"As we know,"_ is followed by a heap of mis-infomation. Anyway, Dictionary is consuming GetHashCode(), not defining it. – H H Dec 28 '13 at 17:18

2 Answers2

3

If you don't specify an IEqualityComparer, Dictionary uses EqualityComparer<T>.Default. This is a comparer that will just call object.GetHashCode on the given argument. So look at Int32.GetHashCode.

usr
  • 168,620
  • 35
  • 240
  • 369
2

GetHashCode is implemented on your TKey type, not on the Dictionary class.

For int.GetHashCode(), which your example uses, it's defined as:

public override int GetHashCode()
{
    return this;
}

Number of backets has nothing to do with the hashcode value.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263