Object.GetHashCode() obsolete?

  • Thread starter Thread starter deutliu
  • Start date Start date
D

deutliu

I'm wondering why the Object class has GetHashCode method? It seems
that the only place that it is used is in the Hashtable class. Now
there is the IEqualityComparer for the new Dictionary class. Can we
say that we don't need the Object.GetHashCode any more?

Ian
 
No, you can't.  And the Hashtable class is not the only place that uses 
it.  And the IEqualityComparer<T> interface requires an implementation of  
GetHashCode(), so the presence of that interface certainly does not mean  
you don't need GetHashCode() any more.

Pete

But the IEqualityComparer<T> has the following method:
int GetHashCode(T obj)
So I don't need to use obj.GetHashCode() to get the hashcode. I can
create my own method to calculate the hashcode from obj.

Where is the Object.GetHashCode used other than the Hashtable class?

Thanks,
Ian
 
But the IEqualityComparer<T> has the following method:
int GetHashCode(T obj)
So I don't need to use obj.GetHashCode() to get the hashcode. I can
create my own method to calculate the hashcode from obj.

Where is the Object.GetHashCode used other than the Hashtable class?

Thanks,
Ian

In the Dictionary class, for example. If you don't specify an
IEqualityComparer when you create the dictionary (which is how you
usually create one), it uses the GetHashCode and Equals methods.
 
But why would you if your equality comparison is exactly the same as used 
by the object?  It would make more sense to just call the object's  
GetHashCode().  And even if you're doing a custom equality comparison (a  
common use of IEqualityComparer<T> of course), the most common way to  
calculate a hash code is to composite one from the hash codes of the  
objects contributing to the equality comparison.


Even if there weren't any examples in .NET, any time anyone wants to write  
a class that uses hashing, it's useful to be able to get a hash code for  
any object.  But, as Göran says, one example is Dictionary<TKey, TValue>.

Pete

Yes, the default Dictionary constructor uses the EqualityComparer that
uses Object.GetHashCode. But it seems that we shouldn't need to define
Object.GetHashCode just because Hashtable/Dictioanry may use it.
IEqualityComparer seems a better way to do this: you define your hash
code calculation only in the place that is needed.

Ian
 
I'm wondering why the Object class has GetHashCode method? It seems
that the only place that it is used is in the Hashtable class. Now
there is the IEqualityComparer for the new Dictionary class. Can we
say that we don't need the Object.GetHashCode any more?

Ian

No, because Hashtables are O(1) complexity. The index has to be
calculated irrespective of the number of objects in the container. The
hashcode is the index.


Regards,
 
Back
Top