How is base.GetHashCode () implemented for a structure?

I recently saw this code in struct, and I was wondering what it actually does base.GetHashCode.

    public override int GetHashCode()
    {
        var hashCode = -592410294;
        hashCode = hashCode * -1521134295 + base.GetHashCode();
        hashCode = hashCode * -1521134295 + m_Value.GetHashCode();
        return hashCode;
    }
+4
source share
2 answers

In coreclr repo this comment :

Action: our hash return algorithm is a bit more complicated. We look for the first non-static field and get its hashcode. If the type does not have non-static fields, we return the hash of the type. We cannot hashcode a static member, because if this element is of the same type as the original type, we end up with an infinite loop.

However, the code is not there, and it seems that not quite what is happening. Example:

using System;

struct Foo
{
    public string x;
    public string y;
}

class Test
{
    static void Main()
    {
        Foo foo = new Foo();
        foo.x = "x";
        foo.y = "y";
        Console.WriteLine(foo.GetHashCode());
        Console.WriteLine("x".GetHashCode());
        Console.WriteLine("y".GetHashCode());
    }
}

The output in my field is:

42119818
372029398
372029397

y - foo.

, int, , .

: , , , , . , / , GetHashCode Equals ( IEquatable<T> ).

+7

ValueType, - . , , :

ValueType.GetHashCode:

/*=================================GetHashCode==================================
**Action: Our algorithm for returning the hashcode is a little bit complex.  We look
**        for the first non-static field and get it hashcode.  If the type has no
**        non-static fields, we return the hashcode of the type.  We can't take the
**        hashcode of a static member because if that member is of the same type as
**        the original type, we'll end up in an infinite loop.
**Returns: The hashcode for the type.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
[System.Security.SecuritySafeCritical]  // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern override int GetHashCode();
+1
source

Source: https://habr.com/ru/post/1688386/


All Articles