Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I never ever use HashSet, should I still implement GetHashCode?

Tags:

c#

I never need to store objects in a hash table. The reason is twofold:

  • coming up with a good hash function is difficult and error prone.
  • an AVL tree is almost always fast enough, and it merely requires a strict order predicate, which is much easier to implement.

The Equals() operation on the other hand is a very frequently used function.

Therefore I wonder whether it is necessary to implement GetHashCode (which I never need) when implementing the Equals function (which I often need)?

like image 396
Dimitri C. Avatar asked May 27 '10 12:05

Dimitri C.


People also ask

Do I need to implement GetHashCode?

Why is it important to override GetHashCode ? It s important to implement both equals and gethashcode, due to collisions, in particular while using dictionaries. if two object returns same hashcode, they are inserted in the dictionary with chaining. While accessing the item equals method is used.

When should we override GetHashCode?

If you're implementing a reference type, you should consider overriding the Equals method if your type looks like a base type, such as Point, String, BigNumber, and so on. Override the GetHashCode method to allow a type to work correctly in a hash table.

Why do we need GetHashCode C#?

GetHashCode() Method with Examples. This method is used to return the hash code for this instance. A hash code is a numeric value which is used to insert and identify an object in a hash-based collection. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.

What happens if we don't override hashCode method?

If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.


1 Answers

my advise - if you don't want to use it, override it and throw new NotImplementedException(); so that you will see where did you need it.

like image 57
Andrey Avatar answered Oct 03 '22 07:10

Andrey