Reputation: 35267
Suppose I have a class T
that I want to use as a key in a Dictionary<T,U>
collection.
What must I implement in T
so that these keys are based on values of T
rather than T
references?
I'm hoping it's just GetHashCode()
.
Upvotes: 3
Views: 163
Reputation: 164291
You must implement GetHashCode() and Equals().
Dictionary is a Hashtable below the covers, so you might want to read this: Pitfalls Of Equals/GetHashCode – How Does A Hash Table Work?
Upvotes: 5
Reputation: 1500505
Either implement Equals
and GetHashCode
or create an appropriate IEqualityComparer<T>
which has the right form of equality matching for your map.
I rather like the IEqualityComparer<T>
route: in many cases there isn't one obviously-right form of equality - you want to treat objects as equal in different ways depending on the situation. In that case, a custom equality comparer is just what you need. Of course, if there is a natural equality operation, it makes sense to implement IEquatable<T>
in the type itself... if you can. (Another benefit of IEqualityComparer<T>
is that you can implement it for types you have no control over.)
Upvotes: 3
Reputation: 41233
If you don't pass any IEqualityComparer<T>
in the dictionary constructor, it will use EqualityComparer<T>.Default
which is defined by MSDN as :
The Default property checks whether type T implements the System.IEquatable(Of T) interface and, if so, returns an EqualityComparer(Of T) that uses that implementation. Otherwise, it returns an EqualityComparer(Of T) that uses the overrides of Object.Equals and Object.GetHashCode provided by T.
So implementing IEquatable<T>
would be my choice (if you implement it it also makes sense to override Equals
and GetHashCode
anyway).
Upvotes: 3
Reputation: 31848
You need to override Equals(object obj)
. It is always expected that you implement GetHashCode
when you modify Equals
. Read this article at MSDN.
Upvotes: 2