How does the <T> dictionary work with key objects that do not implement Equals and GetHashCode?
The base class Object implements Equals and GetHashCode . All classes inherit from Object by default. The dictionary will simply use these implementations.
The standard implementation of references to Equals objects, which are likely to be convenient for your dictionary in most cases.
The basic implementation of GetHashCode is rather naive, in fact, even the documentation states:
The default implementation of the GetHashCode method does not guarantee unique return values ββfor different objects.
Therefore, it is recommended to redefine it yourself if you intend to use the object as a dictionary or hash table key.
Regarding how it works. Remember that GetHashCode is not really critical for implementing a dictionary. hash codes are allowed to collide, this is a kind of point. The hash code is simply used to find the object, whether the equality test that will be used to validate the object is correct at the end. Let's just say for arguments that each object just returned a hash code from 1. They all fall into the same bank in the dictionary, probably in some rather random order (maybe in the order of addition), and it just goes back to use Equals to verify the identity of the object. It would be inefficient, but everything will be fine.
So, if you are looking for efficiency, you should consider redefining GetHashCode, but if it is just a small dictionary and efficiency is not too important, you will be fine to leave it by default.
[All common considerations apply. Itβs better not to override GetHashCode for mutable objects and make 100% sure that objects returning true for Equals () return the same hash code.]
It uses Object.GetHashCode , but note that this hash code is not an identifier for an object:
Standard implementation The GetHashCode method does not guarantee unique return values ββfor different objects. In addition, the .NET Framework does not guarantee a default implementation. The GetHashCode method and its return value will be the same between different versions of .NET. Framework Therefore, the default implementation of this method should not be used as a unique identifier for an object for hashing purposes.
If you want your dictionary to work with reference equality, you can use the following comparator when building the dictionary:
class ReferenceComparer<T> : IEqualityComparer<T> { public bool Equals(T x, T y) { return object.ReferenceEquals(x, y); } public int GetHashCode(T obj) { return obj.GetHashCode(); } }