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
IComparer
interfaces (both the generic and the non-generic one) allow you to compare two instances with each other.The
Compare
method allows you to compare an object itself with another instance. Offcourse, when the current instance is null, you'll get aNullReferenceException
in this case, since you callCompare
on a 'null' instance. A class that implementsIComparer
can overcome this problem.So, when you implement the IComparer interface, you'll have a class which has a 'Compare' method, which can be called like this:
This allows you to do this:
When you instantiate a
Hashtable
with the constructor where you specify theIEqualityComparer
instance, this means that the givenIEqualityComparer
will be used to determine whether a certain key is already present in the Hashtable.Otherwise, the Compare method of the key-object will be used.
The
IComparable
interface 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 usesIEqualityComparer
let you give a specificEquals
/GetHashCode
that can be different than the ones defined by your object. Normally theHashtable
will use your object overriddenEquals
andGetHashCode
(or the baseobject
Equals
andGetHashCode
).To make an example, the standard string compares in case sensitive way (
"A"
!="a"
), but you could make anIEqualityComparer
helper 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.InvariantCultureIgnoreCase
and all the other static methods ofStringComparer
that return aStringComparer
object that implements theIComparer
,IEqualityComparer
,IComparer<string>
,IEqualityComparer<string>
)As a note, the
Hashtable
uses aIEqualityComparer
optional parameter, not the generic versionIEqualityComparer<T>
, becauseHashtable
is pre-generics.