A
A
Aleviy2021-11-10 00:24:40
C++ / C#
Aleviy, 2021-11-10 00:24:40

Difference of CompareTo() in IComparable and Equals() in IEquatable?

You need to compare a type parameter in a generic method. What is the difference between these two methods for comparison?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Makarov, 2021-11-10
@Aleviy

IComparable is designed to establish an order relationship between objects that implement this interface, or, roughly speaking, to sort. Those. when for two given objects A and B you can argue that A < B OR A == B OR A > B.
IEquatable is designed to establish an equality relationship. When for two given objects A and B you can argue that A == B or A != B.
Not for all data types you want and can set an order relation, while for most types with value-semantics you want have an equality/inequality relation. This is such a common and necessary thing that C# entries will automatically implement IEquatable for you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question