Home > Net >  How is Object.Equals() implemented "in the end"?
How is Object.Equals() implemented "in the end"?

Time:04-28

Out of curiosity I wanted to see how the Object.Equals() method is implemented.

So I've browsed the source code of Object which finally led me to RuntimeHelpers.Equals(). But the Equals method of RuntimeHelpers is implemented externally without a Dllimport attribute.

Where can I find the "extern" implementation of RuntimeHelpers.Equals()?

CodePudding user response:

You'll find that implemented in the runtime itself. A good entry point when looking for the implementations of these extern methods is ecalllist.h. Here we find:

FCFuncElement("Equals", ObjectNative::Equals)

So it's implemented by ObjectNative::Equals, which we find in objectnative.cpp:

FCIMPL2(FC_BOOL_RET, ObjectNative::Equals, Object *pThisRef, Object *pCompareRef)
{
    CONTRACTL
    {
        FCALL_CHECK;
        INJECT_FAULT(FCThrow(kOutOfMemoryException););
    }
    CONTRACTL_END;

    if (pThisRef == pCompareRef)
        FC_RETURN_BOOL(TRUE);

    // Since we are in FCALL, we must handle NULL specially.
    if (pThisRef == NULL || pCompareRef == NULL)
        FC_RETURN_BOOL(FALSE);

    MethodTable *pThisMT = pThisRef->GetMethodTable();

    // If it's not a value class, don't compare by value
    if (!pThisMT->IsValueType())
        FC_RETURN_BOOL(FALSE);

    // Make sure they are the same type.
    if (pThisMT != pCompareRef->GetMethodTable())
        FC_RETURN_BOOL(FALSE);

    // Compare the contents (size - vtable - sync block index).
    DWORD dwBaseSize = pThisMT->GetBaseSize();
    if(pThisMT == g_pStringClass)
        dwBaseSize -= sizeof(WCHAR);
    BOOL ret = memcmp(
        (void *) (pThisRef 1),
        (void *) (pCompareRef 1),
        dwBaseSize - sizeof(Object) - sizeof(int)) == 0;

    FC_GC_POLL_RET();

    FC_RETURN_BOOL(ret);
}
FCIMPLEND
  • Related