Provide a Type-Specific Equals Method for Value Equality

When you are implementing value equality in a type, you typically override the Equals method that is defined inSystem.Object.  It has the following signature:
1
public override bool Equals(object obj)
You should also add a type-specific Equals method.  For completeness, you can indicate that your class implementsIEquatable<T>, which includes the type-specific Equals method.
1
public class Dog : IEquatable<Dog>
Below is a complete example, showing us the override of System.Object.Equals, as well as the type-specific Equalsmethod.  Note that the generic Equals method calls the type-specific version.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
// System.Object.Equals
public override bool Equals(object obj)
{
    return this.Equals(obj as Dog);
}
 
// IEquatable<Dog>.Equals
public bool Equals(Dog d)
{
    if (d == null)
        return false;
 
    return (Name == d.Name) && (Age == d.Age);
}