Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between IComparable & IEquatable interfaces?

Both the interfaces seem to compare objects for equality, so what are the major differences between them?

like image 250
SoftwareGeek Avatar asked Mar 09 '10 15:03

SoftwareGeek


People also ask

What is IComparable?

The IComparable interface defines a generalized type-specific comparison method that a value type or class implements to order or sort its instances. The IComparable is implemented by types whose values can be ordered or sorted. The interface requires the CompareTo method to be implemented.

Why do we use IComparable in C#?

Use the IComparable Interface in C# to sort elements. It is also used to compare the current instance with another object of same type. It provides you with a method of comparing two objects of a particular type. Remember, while implementing the IComparable interface, CompareTo() method should also be implemented.

How does IComparer work in C#?

The IComparer. Compare method requires a tertiary comparison. 1, 0, or -1 is returned depending on whether one value is greater than, equal to, or less than the other. The sort order (ascending or descending) can be changed by switching the logical operators in this method.

What does CompareTo return in C#?

CompareTo() method in C# is used to compare this instance to a specified object or another Int16 instance and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object or the other Int16 instance.


1 Answers

IEquatable tests whether two objects are equal.

IComparable imposes a total ordering on the objects being compared.

For example, IEquatable would tell you that 5 is not equal to 7. IComparable would tell you that 5 comes before 7.

like image 73
Greg D Avatar answered Sep 23 '22 13:09

Greg D