Will the <TKey, TValue> dictionary use TKey.Equals and TKey.GetHashCode?

I implemented the dictionary as follows:

Dictionary<ErrorHashKey, ErrorRow> dictionary; 

I defined Equals() and GetHashCode() in the ErrorHashKey class. I am currently writing some documentation for a project and came to it from the IEqualityComparer Interface doc :

The dictionary requires the implementation of equality to determine whether the keys are the same. You can specify the implementation of the common IEqualityComparer interface using a constructor that accepts a comparison parameter; if you do not specify an implementation, the standard delimiter is EqualityComparer.Default used. If the TKey type implements a common System.IEquatable interface file, the default mapping is used.

I am not doing anything as stated in the documentation (or at least I don't think I am). I do not pass the comparison in the constructor parameter, and I do not create the mapping EqualityComparer.Default .

Is the System.IEquatable<T> generic interface automatically implemented in each class? Should I define an implementation of IEqualityComparer<T> ?

+4
source share
2 answers

The default component will call object.Equals or object.GetHashCode (your overridden methods) if IEquatable<T> not implemented. This is described in the documentation for EqualityComparer<T>.Default . You do not need to do anything, and no, IEquatable<T> will not be automatically implemented in your class.

+7
source

Answer ID in your question:

if you do not specify an implementation, the default equality is the default EqualityComparer.Default comparator

EqualityComparer.Default uses the Equals method if you do not implement IEquatable.

The Default property checks whether the type T implements System.IEquatable and, if so, returns the EqualityComparer that uses this implementation. Otherwise, returns EqualityComparer, which uses the Object.Equals and Object.GetHashCode overrides provided by T.

Source: http://msdn.microsoft.com/en-us/library/ms224763(v=vs.110).aspx

+1
source

All Articles