0

I need a "Reference Set," that is, a set that is pretty much a Hash Set but uses it's object's references rather than their hash codes. Where can I find such a class, or how can I implement one? For clarification, I don't care if it works internally like a hash set using references, I just want it to behave like it from the outside. I'd rather not use external libraries, but links to the source code of libraries that have such a set would be welcome (so I can use that to figure out how to implement one myself).

Anonymous
  • 491
  • 2
  • 12
  • 3
    This feels like a XY Problem - https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem . **Why** do you want this? – mjwills Apr 11 '18 at 22:06
  • Can you talk us through why you can't use `HashSet` using `ReferenceEqualityComparer`? https://stackoverflow.com/questions/1890058/iequalitycomparert-that-uses-referenceequals – mjwills Apr 11 '18 at 22:13
  • @mjwills I didn't know HashSets could accept IEqualityComparers. Thanks for the quick solution. – Anonymous Apr 11 '18 at 22:22

1 Answers1

2

The standard HashSet<T> allows you to provide a custom comparer, and that comparer is responsible for hashing and performing equality checks on set elements. Give it an identity comparer, and you'll get the functionality you describe.

public sealed class IdentityComparer<T> : IEqualityComparer<T>
    where T : class
{
    public bool Equals(T x, T y)
    {
        return ReferenceEquals(x, y);
    }

    public int GetHashCode(T obj)
    {
        return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
    }
}
Mike Strobel
  • 25,075
  • 57
  • 69
  • "The RuntimeHelpers.GetHashCode method always calls the Object.GetHashCode", so how is different from the standard HashSet ? – H H Apr 11 '18 at 22:23
  • 1
    @HenkHolterman That's exactly how it's different. Given e.g. a string, it will call the `Object.GetHashCode` method, meaning non-virtually, *not* the `String.GetHashCode` implementation that a virtual call to `GetHashCode` would result in. –  Apr 11 '18 at 22:27
  • This is exactly what I need, thanks! – Anonymous Apr 11 '18 at 22:29
  • @hvd - ok, fair point. Still an XY question though. Under what circumstance will this be better? For `HashSet` for example? – H H Apr 11 '18 at 22:30