Equals()
is called on an object that does not implement Equals()
.
When comparing objects, developers developers usually want to compare properties of objects. However, calling Equals()
on a class (or any super class/interface) that does not explicitly implement Equals()
results in a call to the Equals()
method inherited from System.Object
. Instead of comparing object member fields or other properties, Object.Equals()
compares two object instances to see if they are the same. Although there are legitimate uses of Object.Equals()
, it is often an indication of buggy code.
Example 1:
public class AccountGroup
{
private int gid;
public int Gid
{
get { return gid; }
set { gid = value; }
}
}
...
public class CompareGroup
{
public bool compareGroups(AccountGroup group1, AccountGroup group2)
{
return group1.Equals(group2); //Equals() is not implemented in AccountGroup
}
}
[1] Standards Mapping - Common Weakness Enumeration - (CWE) CWE ID 398