Skip to content

GetHashCode is not working correctly for class objects #1416

Closed
nanoframework/nf-interpreter
#2840
@josesimoes

Description

@josesimoes

Library/API/IoT binding

interpreter

Visual Studio version

No response

.NET nanoFramework extension version

No response

Target name(s)

No response

Firmware version

No response

Device capabilities

No response

Description

When calling GetHashCode for the same class object, depending on the call, it produces different hashes.
This was found incidentally when running tests around nanoframework/System.Collections#123.

Code to reproduce this:

public static void Hashtable_ClassAsKey()
{
        SomeKey key = new SomeKey(i);

        var value = key.GetHashCode();

        Debug.WriteLine($"{(int)key.GetHashCode()} vs {value}");
}

public class SomeKey
{
    private readonly int _value;
    public SomeKey() { }

    public SomeKey(int value)
    {
        _value = value;
    }
    public int GetValue => _value;
}

Output from above is for example: 586458527 vs 1002131715 which is wrong.

How to reproduce

Code to reproduce this:

public static void Hashtable_ClassAsKey()
{
        SomeKey key = new SomeKey(i);

        var value = key.GetHashCode();

        Debug.WriteLine($"{(int)key.GetHashCode()} vs {value}");
}

public class SomeKey
{
    private readonly int _value;
    public SomeKey() { }

    public SomeKey(int value)
    {
        _value = value;
    }
    public int GetValue => _value;
}

Output from above is for example: 586458527 vs 1002131715 which is wrong.

Expected behaviour

Calling GetHashCode for the same class object has to return the same hash value.

Screenshots

No response

Sample project or code

No response

Aditional information

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions