Thursday, September 17, 2009

Object.GetHashCode, Object.Equals, operator==, and related

After some research, I summarize some points below as guidelines.

1. Object.Equals method and operator== are supposed to be used interchangeably. (It applies to all the .net classes) Therefore, when implementing a new class, it's a good idea to always implement both of them.
Equals() is usually used (implemented) for value equality and Operator== is used for reference equality by default. When a type is an immutable type (e.g. String), overloading Operator== to compare value equality makes sense.

Guidelines for Overloading Equals() and Operator==
http://msdn.microsoft.com/en-us/library/ms173147%28VS.80%29.aspx

Override equals on overloading operator equals
http://msdn.microsoft.com/en-us/library/ms182357%28VS.80%29.aspx

When should I use == and when should I use Equals
http://blogs.msdn.com/csharpfaq/archive/2004/03/29/102224.aspx

2. It is important to override GetHashCode when overriding Equals method. Although failure to do so will not always break your code, things can go wrong if the class is used as a key in a dictionary etc. In that situation, if the hash-code for two items does not match, they may never be considered equal (Equals will never be called). To write the GetHashCode, we need to make sure that: if two objects are equal, then they must return the same value for GetHashCode. On the other hand, we do NOT have to make sure two different objects always return different values for GetHashCode.

Why is it important to override GetHashCode when Equals method is overriden in C#
http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overriden-in-c

3. A good implementation of GetHashCode that can be used in many situations:
public int GetHashCode()
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + field1.GetHashCode();
hash = hash * 23 + field2.GetHashCode();
hash = hash * 23 + field3.GetHashCode();
return hash;
}
What is the best algorithm for an overridden System.Object.GetHashCode
http://stackoverflow.com/questions/263400#263416

4. Implementing IEquatable Properly
http://www.codeproject.com/KB/dotnet/IEquatable.aspx

No comments: