Skip to content

ValueTuple with more than 8 fields calculates its hash code incorrectly #13087

@dioptryk

Description

@dioptryk

Consider the following code:

Console.WriteLine((  1, 2, 3, 4, 5, 6, 7, 8).GetHashCode());
Console.WriteLine((777, 2, 3, 4, 5, 6, 7, 8).GetHashCode()); // different result
		
Console.WriteLine((  1, 2, 3, 4, 5, 6, 7, 8, 9, 10).GetHashCode());
Console.WriteLine((777, 2, 3, 4, 5, 6, 7, 8, 9, 10).GetHashCode()); // same result

The ValueTuple ignores first N-8 fields when calculating hash code. It even says so in a comment in ValueTuple.cs. The offending code is:

if (size >= 8) { return rest.GetHashCode(); }

To be honest, this seems like a bug to me, since this behaviour is described nowhere but the source. We were using tuple syntax to calculate hash codes of several class members and just noticed, that even with some fields changed, the hashes were still equal.. I understand this will have performance implications, but still I find the GetHashCode() unusable in its current state for "big" tuples. This is wrong for both .NET Framework and Core.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions