Skip to content

HashSet<int>.CreateSetComparer implementation is not symmetric #69218

@jaredpar

Description

@jaredpar

Description

The implementation of HashSetEqualityComparer<T>.Equals does not consider the Count of collections when they have different comparers. That means it's possible for two sets to compare equals when they have a different count of items. That leads to the implementation not being symmetric.

Reproduction Steps

var x = new HashSet<int>(new Comparer());
x.Add(1);
var y = new HashSet<int>(new Comparer());
y.Add(1);
y.Add(2);

var comparer = HashSet<int>.CreateSetComparer();

Console.WriteLine(comparer.Equals(x, y));
Console.WriteLine(comparer.Equals(y, x));

internal sealed class Comparer : IEqualityComparer<int>
{
    public bool Equals(int x, int y) => x == y;
    public int GetHashCode(int obj) => obj.GetHashCode();
}

Sharplab demonstration

Expected behavior

The expected behavior is to print

False
False

Actual behavior

This code prints:

False
True

Regression?

No

Known Workarounds

No response

Configuration

net6.0

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions