Rule Definition
Types that define a custom sort order implement the IComparable interface. The CompareTo method returns an integer value that indicates the correct sort order for two instances of the type. This rule identifies types that set a sort order. Setting a sort order implies that the ordinary meaning of equality, inequality, less-than, and greater-than don't apply. When you provide an implementation of IComparable, you must usually also override Equals so that it returns values that are consistent with CompareTo.
The CLR does not implement static methods in interface contracts or double-virtual dispatch, or the ability to put an operator constraint on a generic type parameter. And therefore multiple solutions have evolved to solve the equality/inequality problem.
Remediation
Override the 'Equals' and the comparison operators
Violation Code Sample
public class Foo: IComparable
{
public int CompareTo(object obj) { /* ... */ }
} //Violation: No overriding of Equals and comparison operators
Fixed Code Sample
public class Foo: IComparable
{
public int CompareTo(object obj) { /* ... */ }
public override bool Equals(object obj)
{
var other = obj as Foo;
if (object.ReferenceEquals(other, null))
{
return false;
}
return this.CompareTo(other) == 0;
}
public int GetHashCode() { /* ... */ }
public static bool operator == (Foo left, Foo right)
{
if (object.ReferenceEquals(left, null))
{
return object.ReferenceEquals(right, null);
}
return left.Equals(right);
}
public static bool operator > (Foo left, Foo right)
{
return Compare(left, right) > 0;
}
public static bool operator < (Foo left, Foo right)
{
return Compare(left, right) < 0;
}
public static bool operator != (Foo left, Foo right)
{
return !(left == right);
}
}
Reference
https://cwe.mitre.org/data/definitions/581
https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1036
Related Technologies
Technical Criterion
CWE-1097 - Persistent Storable Data Element without Associated Comparison Control Element
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.