Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding GetHashCode [duplicate]

As you know, GetHashCode returns a semi-unique value that can be used to identify an object instance in a collection. As a good practice, it is recommended to override this method and implement your own.

My question is - do you override this method when working on custom objects? If so, what algorithm do you use to generate the unique ID?

I was thinking about generating a GUID and then getting integer data from that identificator.

like image 647
Den Delimarsky Avatar asked Nov 21 '10 21:11

Den Delimarsky


People also ask

Should I override 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 GetHashCode () method should be overridden along with equals () method in each DTO class?

You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object. hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

What happens if we override only equals?

Overriding only equals() method without overriding hashCode() causes the two equal instances to have unequal hash codes, which violates the hashCode contract (mentioned in Javadoc) that clearly says, if two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two ...


2 Answers

If you use resharper it can generate the GetHashCode(), Equals and operator method bodies for you.

Access this menu by pressing Alt+Insert.

http://www.jetbrains.com/resharper/webhelp/Code_Generation__Equality_Members.html

like image 131
Winston Avatar answered Oct 04 '22 07:10

Winston


When you override GetHashCode() you also need to override Equals(), operator== and operator!= . And be very careful to meet all the requirements for those methods.

The guidelines are here on MSDN. Most important quote:

It is not a good idea to override operator == in mutable types.

like image 37
Henk Holterman Avatar answered Oct 04 '22 08:10

Henk Holterman