A HashSet<T> can determine in O(1) whether it contains a certain item. If I override Equals() and GetHashCode() on my custom class, I can have an object A and another object A’ that are not equal by identity but for which Equals() returns true and GetHashCode() returns the same hash code.
Now, given that A is in the hash set, I want to retrieve A in O(1) given A’ (which is equal to A from the perspective of the hash set).
var a = new MyClass("A");
var a_prime = new MyClass("A");
Debug.Assert(a.Equals(a_prime));
Debug.Assert(a.GetHashCode() == a_prime.GetHashCode());
var set = new HashSet<MyClass>();
set.Add(a);
Debug.Assert(set.Contains(a_prime));
// This:
var retrieved_a = set.Get(a_prime);
How to do this?
(Note that this has not the answer I’m looking for, and this has no answers at all.)
Some background information: I want to use the set to intern my own objects the same way C# interns strings: equal objects need only one instance. This way I can append metadata to such an object and be sure that there is no other equal instance anywhere without that metadata.
There is no method on
HashSetthat does what you want.You can use a
Dictionaryinstead: