Say for a Point2 class, and the following Equals:
public override bool Equals ( object obj )
public bool Equals ( Point2 obj )
This is the
Likely you want to both override Equals(object) and define Equals(MyType) because the latter avoids boxing. And override the equality operator.
.NET Framework Guidelines book (2nd ed) has more coverage.
Lie Daniel L said,
public override bool Equals(object obj) {
Point2 point = obj as Point2; // Point2? if Point2 is a struct
return point != null && this.Equals(point);
}
public bool Equals(Point2 point) {
...
}
There is also a Fody plugin Equals.Fody that generates Equals() and GetHashCode() automatically
The technique I've used that has worked for me is as follows. Note, I'm only comparing based on a single property (Id) rather that two values. Adjust as needed
using System;
namespace MyNameSpace
{
public class DomainEntity
{
public virtual int Id { get; set; }
public override bool Equals(object other)
{
return Equals(other as DomainEntity);
}
public virtual bool Equals(DomainEntity other)
{
if (other == null) { return false; }
if (object.ReferenceEquals(this, other)) { return true; }
return this.Id == other.Id;
}
public override int GetHashCode()
{
return this.Id;
}
public static bool operator ==(DomainEntity item1, DomainEntity item2)
{
if (object.ReferenceEquals(item1, item2)) { return true; }
if ((object)item1 == null || (object)item2 == null) { return false; }
return item1.Id == item2.Id;
}
public static bool operator !=(DomainEntity item1, DomainEntity item2)
{
return !(item1 == item2);
}
}
}