D
D
Denis Bredun2020-07-04 00:37:32
C++ / C#
Denis Bredun, 2020-07-04 00:37:32

How is the hashcode generated by default, i.e. in the object class, in C#?

Hello, Khabrachan! I looked all over the Internet hoping to find something about generating a hash code in the object class, but, in the end, I came across only articles with Java, not C #, and even the articles with Jav had their own troubles. So, please, tell me, not far from looking, how does the generation of hash codes in object in C# (version 8.0) work anyway? Is there a random number generation, or is the address of the object converted to an integer form, or what? Explain, please. =' )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Korotenko, 2020-07-04
@Luffy1

/// <summary>Служит хэш-функцией по умолчанию.</summary>
    /// <returns>Хэш-код для текущего объекта.</returns>
    [__DynamicallyInvokable]
    public virtual int GetHashCode()
    {
      return RuntimeHelpers.GetHashCode(this);
    }

https://stackoverflow.com/questions/720177/default...
It also calls this native code.
FCIMPL1(INT32, ObjectNative::GetHashCode, Object* obj) {  
    CONTRACTL  
    {  
        THROWS;  
        DISABLED(GC_NOTRIGGER);  
        INJECT_FAULT(FCThrow(kOutOfMemoryException););  
        MODE_COOPERATIVE;  
        SO_TOLERANT;  
    }  
    CONTRACTL_END;  

    VALIDATEOBJECTREF(obj);  

    DWORD idx = 0;  

    if (obj == 0)  
        return 0;  

    OBJECTREF objRef(obj);  

    HELPER_METHOD_FRAME_BEGIN_RET_1(objRef);        // Set up a frame  

    idx = GetHashCodeEx(OBJECTREFToObject(objRef));  

    HELPER_METHOD_FRAME_END();  

    return idx;  
}  
FCIMPLEND

See also this article.
see Knuth Vol 2 p16 (3.2.1.2 Theorem A)

https://habr.com/ru/post/188038/
https://codingsight.com/the-origin-of-gethashcode-...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question