Search code examples
c#.netclrbase-class-library

What does RuntimeHelpers.GetHashCode do


The RuntimeHelpers.GetHashCode(object) method allows generating hash codes based on the identity of an object. MSDN states:

The RuntimeHelpers.GetHashCode method always calls the Object.GetHashCode method non-virtually, even if the object's type has overridden the Object.GetHashCode method.

[MethodImpl(MethodImplOptions.InternalCall)]
[SecuritySafeCritical]
public static extern int GetHashCode(object o);

However, when inspecting the Object.GetHashCode() method using Reflector (.NET 4.0), we'll see the following code:

public virtual int GetHashCode()
{
    return RuntimeHelpers.GetHashCode(this);
}

This makes me believe that the MSDN documentation is wrong, since calling Object.GetHashCode from within the RuntimeHelpers.GetHashCode(object) would cause a stack overflow.

So what is the actual behavior of RuntimeHelpers.GetHashCode(object) and how does it work? How does it calculate the hash?


Solution

  • I think the MSDN documentation is trying to describe the behaviour, not the implementation. The key point: RuntimeHelpers returns the default implementation that you would get were object.GetHashCode() not overridden.

    This is really useful if, for example, you want to build a reference equality lookup, even for types that have overridden Equals and GetHashCode. I do this in a serializer that I maintain, using RuntimeHelpers.GetHashCode() and Object.ReferenceEquals.