0

I want to have dictionary Dictionary<MyType,Something> or hash set HashSet<MyType>. In my application it holds that any two different instances of type MyType are never equal. Is it safe to use default implementation of GetHashCode and Equals in this case?

I am not sure how GetHashCode is implemented. But I always imagined that it is something like memory location of the object. Is this true?

If so then I would like to know what happens when garbage collector relocates the object? Can this happen? Could this cause that the object of MyType cannot be found in dictionary anymore?

B0B
  • 1
  • 2
  • I did not ask about what Equals does. I know this very well. I am unsure about unsure about GetHashCode and whether garbage collector can relocate the object and change the return value of GetHashCode. I have done minor edit to title and text of question to make this more obvious. – B0B May 25 '18 at 15:40
  • Sorry @B0B, Stackoverflow has become a mess of people not even trying to help but instead thinking that the goal is to just close questions. To answer your question, Object.GetHashCode "Serves as a hash function for a particular object, and is suitable for use in algorithms and data structures that use hash codes, such as a hash table." It will compare them as reference types. What you are doing is proper as long as you are always looking them up by reference - as that's how they are also Equal. – TheSoftwareJedi May 25 '18 at 16:33
  • Any garbage collection moving around will not affect an Object's hashcode. – TheSoftwareJedi May 25 '18 at 16:34
  • @TheSoftwareJedi Thank you. Your comment helped me. – B0B May 30 '18 at 12:04

0 Answers0