dotnet / dotnet/dotnet-api-docs

Advice on how to implement comparison operators for a type whose CompareTo is inconsistent with Equals

Open
#2,937 3 comments 0 reactions 0 assignees View on GitHub
area-System.Runtime Pri3
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

Posted from [this issue](https://github.com/MicrosoftDocs/visualstudio-docs/issues/3728).

The Visual Studio Code Analysis documentation for [CA1036](https://github.com/MicrosoftDocs/visualstudio-docs/blob/master/docs/code-quality/ca1036-override-methods-on-comparable-types.md) should include advice on how comparison operators should be implemented in the following circumstance.

- A custom number class (not from the base class library) represents a number by its significand and exponent.
- It overrides Object.Equals with a method that compares the significand and exponent for equality.
- It has a CompareTo method that does a numerical comparison of the two numbers, which is a non-total ordering that is inconsistent with Equals.
- It implements the "<", "<=", ">=", and ">" operators to do comparisons that are consistent with CompareTo.

Should it implement the "==" and "!=" operators to be consistent with Equals or with CompareTo, or should it refrain from implementing those operators?

What if CompareTo instead does a total ordering of the two numbers (making it consistent with Equals)? Can it implement the "<", "<=", ">=", and ">" operators to do a numerical comparison rather than a total ordering, if a numerical comparison makes more sense? If so, should the "==" and "!=" operators be implemented to be consistent with Equals, with a non-total comparison, or with a total ordering comparison, or not be implemented?

For the purpose of this issue, an example of the number class is found in my library's EDecimal class ([EDecimal.cs](https://github.com/peteroupc/Numbers/blob/master/Numbers/PeterO/Numbers/EDecimal.cs), [EDecimalExtra.cs](https://github.com/peteroupc/Numbers/blob/master/Numbers/PeterO/Numbers/EDecimalExtra.cs)), except that it doesn't implement the "<", "<=", ">=", and ">" operators at the time of this writing.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.