PROBLEM
I need a method for generating keys for a dictionary of objects. However, I have a few requirements that are making this a bit difficult. Here is the scenario:
- The Dictionary is a list of reference type objects.
- The Dictionary is
private
, within a static class. - External code needs to obtain a key to specific objects within the dictionary, but MUST NOT have access to the objects within the dictionary, or the dictionary itself.
- Given a specific object within the dictionary, the key must be consistently re-calculable/derivable. If properties on the object change, the key MUST NOT CHANGE.
- Conversely, if a new object is created that can evaluate to being
equal
to another object within the dictionary, the key must be different since they are two, separate objects. - This implementation must be thread safe.
NON-SOLUTIONS
Solution #1
All .Net objects contain a method called .GetHashCode()
, which returns an integer value. You can use this as a key.
Problem
Not possible. MSDN States:
Two objects that are equal return hash codes that are equal.
This breaks req #5 and I assume (but not tested) req. #4. I would love to have an option like this, if it could meet these rules.
Solution #2
Convert the pointer to the object to an int
and use that as a key.
Problem
This breaks the essence of req. #3. Passing pointers, and using them as keys doesn't feel safe.
Solution #3
Convert the pointer to the object to an integer hash the value and use the hash as a key.
Problem
Although this doesn't break any rules, I'd prefer to avoid accessing pointers since this would involve using unsafe
code. I'm not opposed to using unsafe code if I have to, but I'd prefer to avoid it if at all possible.
CONCLUSION
Maybe my requirements are a bit picky. There has to be some reasonable way of deriving a key from a unique object. Has anyone ever experienced such a scenario and solved this dilemma?