Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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>?

like image 553
Chris Dargis Avatar asked Feb 20 '23 10:02

Chris Dargis


1 Answers

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.

like image 173
Tim S. Avatar answered Mar 16 '23 07:03

Tim S.