Reputation: 6043
I have implemented a Dictionary as follows:
Dictionary<ErrorHashKey, ErrorRow> dictionary;
I have defined Equals()
and GetHashCode()
in the ErrorHashKey
class. I am currently writing up some documentation for the project, and came accross this from the IEqualityComparer Interface doc:
Dictionary requires an equality implementation to determine whether keys are equal. You can specify an implementation of the IEqualityComparer generic interface by using a constructor that accepts a comparer parameter; if you do not specify an implementation, the default generic equality comparer EqualityComparer.Default is used. If type TKey implements the System.IEquatable generic interface, the default equality comparer uses that implementation.
I am not doing anything that the documentation specifies (or at least I don't think I am). I do not pass a comparer in the constructor parameter nor do I create an EqualityComparer.Default
comparer.
Is the System.IEquatable<T> generic interface
automatically implemented in every class created? Should I be defining an implementation of IEqualityComparer<T>
?
Upvotes: 4
Views: 379
Reputation: 13286
The answer id in your question:
if you do not specify an implementation, the default generic equality comparer EqualityComparer.Default is used
EqualityComparer.Default is using the Equals
method if you're not implementing IEquatable.
The Default property checks whether type T implements the System.IEquatable interface and, if so, returns an EqualityComparer that uses that implementation. Otherwise, it returns an EqualityComparer that uses the overrides of Object.Equals and Object.GetHashCode provided by T.
Source: http://msdn.microsoft.com/en-us/library/ms224763(v=vs.110).aspx
Upvotes: 1
Reputation: 56536
The default comparer will call object.Equals
or object.GetHashCode
(your overridden methods) if IEquatable<T>
is not implemented. This is documented at the documentation for EqualityComparer<T>.Default
. You don't need to do anything extra, and no, IEquatable<T>
is not automatically implemented in your class.
Upvotes: 7