Implementing Equals in C#
While working on refactorings, I often notice domain objects that implement Equals incorrectly. Below is a sample implementation of Equals. The key points are that Equals should not throw an exception if obj is null or of the wrong type. Also note the different patterns for comparing reference and value members. See pages 154-160 of Richter's excellent Applied Microsoft .NET Framework Programming for more details, including different patterns for reference or value objects:
public override bool Equals(object obj)
{
if (obj == null) return false;
if (this.GetType() != obj.GetType()) return false;
// safe because of the GetType check
Customer cust = (Customer) obj;
// use this pattern to compare reference members
if (!Object.Equals(Name, cust.Name)) return false;
// use this pattern to compare value members
if (!Age.Equals(cust.Age)) return false;
return true;
}