Override methods on comparable types
Override methods on comparable types
Microsoft docsDescription
Types that define a custom sort order implement the System.IComparable interface. The System.IComparable.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 System.IComparable, you must usually also override System.Object.Equals so that it returns values that are consistent with System.IComparable.CompareTo. If you override System.Object.Equals and are coding in a language that supports operator overloads, you should also provide operators that are consistent with System.Object.Equals.
Cause
A type implements the System.IComparable interface and does not override System.Object.Equals or does not overload the language-specific operator for equality, inequality, less-than, or greater-than. The rule does not report a violation if the type inherits only an implementation of the interface.
By default, this rule only looks at externally visible types, but this is configurable.
How to fix violations
To fix a violation of this rule, override System.Object.Equals. If your programming language supports operator overloading, supply the following operators:
op_Equalityop_Inequalityop_LessThanop_GreaterThan
Example
// In C#, implement these operators.
public static bool operator ==(SampleClass? one, SampleClass? other) { }
public static bool operator !=(SampleClass? one, SampleClass? other) { }
public static bool operator <(SampleClass? one, SampleClass? other) { }
public static bool operator >(SampleClass? one, SampleClass? other) { }When to suppress
It's safe to suppress a warning from rule CA1036 when the violation is caused by missing operators and your programming language does not support operator overloading. If you determine that implementing the operators does not make sense in your app context, it's also safe to suppress a warning from this rule when it fires on equality operators other than op_Equality. However, you should always override op_Equality and the == operator if you override System.Object.Equals.