It makes total sense if that code is inside Object.Equals
override and you don't want to invoke the equality operator (which might, for example, erroneously call Equals
). Casting to object allows to call standard equality operator, which compares references.
Normally, you would use Object.ReferenceEquals
to compare an instance of an object to null
inside Equals
override.
For example, this would cause a stack overflow:
public class Point {
public override bool Equals (object other) {
var otherPoint = other as Point;
if (other == null)
return false;
//...
}
public static bool operator == (Point l, Point r) {
//...
//null checks
if (!l.Equals(r))
return false;
}
}
In the above example equality operator calls Equals
and because otherPoint
variable is of type Point
, it would invoke the equality operator, causing infinite recursion.
Normally, when you override Equals
and define the equality operator, you would put the comparison logic in the operator and invoke that from the Equals
override. Bear in mind that it's recommended for the class to be immutable if both are overridden.
public class Point {
public override bool Equals (object other) {
var otherPoint = other as Point;
return this == otherPoint;
}
//must override GetHashCode() as well
public static bool operator == (Point l, Point r) {
if (Object.ReferenceEquals(l, null) && Object.ReferenceEquals(r, null))
return true;
if (Object.ReferenceEquals(l, null) || Object.ReferenceEquals(r, null))
return false;
//actual equality checks
}
public static bool operator != (Point l, Point r) {
return !(l==r);
}
}