Search code examples
c#algorithmmethodsoverridinggethashcode

Overriding GetHashCode


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.


Solution

  • 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.