the ‘Equal’ and ‘GetHashcode’ method are exist in the object class, and our type inherit the object base class.
what’s the different between implement the two methods of the object directly and using the IComparer interface?
if we overriding object’s Equal and GetHashCode , and push to a hashtable , it will use the overring ‘s equal method?
what’ the differents of new a hashtable with the IEqualityComparer constructor?
The
IComparableinterface is used when you need to be able to “sort” objects, and it gives you a method (CompareTo) that tells you if two objects are <, = or > . The constructor that usesIEqualityComparerlet you give a specificEquals/GetHashCodethat can be different than the ones defined by your object. Normally theHashtablewill use your object overriddenEqualsandGetHashCode(or the baseobjectEqualsandGetHashCode).To make an example, the standard string compares in case sensitive way (
"A"!="a"), but you could make anIEqualityComparerhelper class to be able to hash your strings in a case insensitive way. (technically this class is already present in multiple variants: they are calledStringComparer.InvariantCultureIgnoreCaseand all the other static methods ofStringComparerthat return aStringComparerobject that implements theIComparer,IEqualityComparer,IComparer<string>,IEqualityComparer<string>)As a note, the
Hashtableuses aIEqualityCompareroptional parameter, not the generic versionIEqualityComparer<T>, becauseHashtableis pre-generics.