2

I want to subclass HashSet<Point> so that it uses HashSet<Point>.CreateSetComparer() as an IEqualityComparer whenever I use it inside another set.

Basically every time I do this:

var myDict = new Dictionary<MySubclassOfHashSet, Char>();

I want it automatically treated as :

var myDict = new Dictionary<HashSet<Point>, Char>(HashSet<Point>.CreateSetComparer());

As per this question.

I have currently done this manually as follows:

class MySubclassOfHashSet: HashSet<Point> {
    public override bool Equals(object obj) {
      //...
    }
    public override int GetHashCode() {
      //...
    }
}

But it's kind of ugly. Is there an easier way that I'm missing?

Community
  • 1
  • 1
Flash
  • 15,945
  • 13
  • 70
  • 98

1 Answers1

1
    var myDict = new Dictionary<MySubclassOfHashSet<Point>, Char>();

    public sealed class MySubclassOfHashSet<T> : HashSet<T>, IEquatable<MySubclassOfHashSet<T>>
    {
        public override int GetHashCode()
        {
            return Unique.GetHashCode(this);
        }
        public bool Equals(MySubclassOfHashSet<T> other)
        {
            return Unique.Equals(this, other);
        }

        private static readonly IEqualityComparer<HashSet<T>> Unique = HashSet<T>.CreateSetComparer();
    }
Vince
  • 896
  • 5
  • 18
  • Shouldn't you also implement `public override bool Equals(object obj)`? And add annoyingly any parameterized constructors from `HashSet` – NetMage Oct 19 '18 at 21:21