This is my second post about equality comparison methods. The first part, which was about Java equality methods, can be found here. This second post covers the .NET side of things.
In .NET, there is a difference between reference types (classes) and value types (structures). This has some implications for equality comparison, so first I will consider the equality comparison for classes, and then structures.
Reference types
The things to watch for in a .NETEquals method are pretty much the same as for Java: the object passed to Equals method can be null or an instance of another class.My template for an Equals method of a .NET reference type is:
public override bool Equals(object o) {
if (Object.ReferenceEquals(this, o)) {
return true;
}
<class> other = o as <class>;
if (other != null) {
return ( (this.field1.Equals(other.field1) &&
(this.field2.Equals(other.field2) &&
// compare every field in <class>
);
}
return false;
}
Since .NET classes can have an overloaded == operator, you cannot use that to check for reference equality as in Java. Instead, you can use Object.ReferenceEquals, which always works. Also note the use of the as operator, so that you check the type and perform a cast in one call.
Value types
With .NET structures, it is a bit of a different story: structures cannot benull, and there is no such thing as reference equality.My template for an Equals method of a .NET value type is:
public override bool Equals(object o) {
if (o is <class>) {
<class> other = (<class>)anObject;
return ( (this.field1.Equals(other.field1) &&
(this.field2.Equals(other.field2) &&
// compare every field in <class>
);
}
return false;
}