#417 – Provide a Type-Specific Equals Method for Value Equality
September 22, 2011 Leave a comment
When you are implementing value equality in a type, you typically override the Equals method that is defined in System.Object. It has the following signature:
public override bool Equals(object obj)
You should also add a type-specific Equals method. For completeness, you can indicate that your class implements IEquatable<T>, which includes the type-specific Equals method.
public class Dog : IEquatable<Dog>
Below is a complete example, showing us the override of System.Object.Equals, as well as the type-specific Equals method. Note that the generic Equals method calls the type-specific version.
// 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); }