yanghuan/CSharp.lua

Default equality comparer in Dictionary is not used

joelverhagen opened this issue · 0 comments

It appears a reference equals is used by default.

Repro:

internal class Program
{
    private static void Main()
    {
        var a = new Location(5, 10);
        var b = new Location(10, 5);
        var c = new Location(1, 14);
        var d = new Location(1, 14);
        var dictionary = new Dictionary<Location, string>();
        // works: var dictionary = new Dictionary<Location, string>(EqualityComparer<Location>.Default);
        dictionary.TryAdd(a, "a");
        dictionary.TryAdd(b, "b");
        dictionary.TryAdd(c, "c");
        dictionary.TryAdd(d, "d");
        Console.WriteLine(string.Join(" ", dictionary.Values.Order())); // should be "a b c"
    }

    public class Location : IEquatable<Location?>
    {
        public Location(int x, int y)
        {
            X = x;
            Y = y;
        }

        public int X { get; }
        public int Y { get; }

        public override bool Equals(object? obj)
        {
            return Equals(obj as Location);
        }

        public bool Equals(Location? other)
        {
            return other is not null &&
                   X == other.X &&
                   Y == other.Y;
        }

        public override int GetHashCode()
        {
            return X + Y; // simple implementation to allow collisions
        }
    }
}

Actual output:

a b c d

Expected output:

a b c