Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I implement IEquatable, or IComparable?

Tags:

c#

.net

I have a class. The thing that this class is meant to represent is such that we may speak about such things being equal to each other, and we may also come up with a scheme to rank them for purposes of comparison.

However, it so happens that it is rare that one feels the need to rank these things, but one often needs to check if two such things are equal.

So, I can implement both IEquatable for my class as well as IComparable. While IComparable provides some extra functionality, it is very unlikely that anyone will care about this extra functionality. Neither one seemingly provides a clear advantage, either logically or functionality-wise.

Which interface should I implement, IEquatable, IComparable, or both? Why? (I am specifically wondering about framework-wide implications either interface)

This question is similar, but the answers only state the obvious, which doesn't help me.

In case you are wondering, the class is meant to represent a nucleotide. Nucleotides can readily be equated, but they can also be compared (eg. alphabetically).

like image 377
Superbest Avatar asked Jan 18 '14 00:01

Superbest


People also ask

What is the purpose of IComparable interface?

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.

What is the difference between IComparable and IComparer?

IComparer compares two objects that it's given. IComparable is implemented by the object that is being compared, for the purpose of comparing with another one of itself.

How do you implement IComparable?

Implementing IComparable Interface requires:Adding a method CompareTo() which receives an object and returns an integer. The CompareTo() method depending on the comparison: returns 0, if the current instance's property is equal to the temporary variable's property.

What is IEquatable in C#?

The IEquatable<T> interface is used by generic collection objects such as Dictionary<TKey,TValue>, List<T>, and LinkedList<T> when testing for equality in such methods as Contains , IndexOf , LastIndexOf , and Remove . It should be implemented for any object that might be stored in a generic collection.


1 Answers

I would definitely implement IEquatable<T> but skip IComparable/IComparable<T> for now.

As you said there is no one way to compare nucleotides. Someone may need to compare them alphabetically, someone may need another way to sort them. I would rather provide different implementations of IComparer<Nucleotide> to implement IComparable/IComparable<T> itself.

like image 191
MarcinJuraszek Avatar answered Sep 23 '22 13:09

MarcinJuraszek