Search code examples
c#hashgethashcodeiequalitycomparer

Definition of GetHashCode() in C#


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;

Solution

  • 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.