Why is this an issue?
Making a base
call in an overriding method is generally a good idea, but not in GetHashCode
and Equals
for
classes that directly extend object
because those methods are based on the object reference. Meaning that no two objects
that use those base
methods will ever be equal or have the same hash.
Noncompliant code example
public class Point
{
private readonly int x;
public MyClass(int x)
{
this.x = x;
}
public override int GetHashCode()
{
return x.GetHashCode() ^ base.GetHashCode(); //Noncompliant
}
}
Compliant solution
public class Point
{
private readonly int x;
public MyClass(int x)
{
this.x = x;
}
public override int GetHashCode()
{
return x.GetHashCode();
}
}
Exceptions
This rule doesn’t report on guard conditions checking for reference equality.
public class Point
{
public override bool Equals(object obj)
{
if (base.Equals(obj)) // Compliant, although it could be replaced with object.ReferenceEquals(obj, this), which is clearer
{
return true;
}
...
}
}