15

What is the best practice in C# starting from version 4.0 when writing a comparer class :

a. Should we inherit from Comparer abstract class ? or

b. Should we implement IComparer interface.

What are the pros and cons?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sebastian Widz
  • 1,962
  • 4
  • 26
  • 45

2 Answers2

15

I would recommend that you extend the Comparer<T> class instead of implementing the IComparer<T> interface, as does Microsoft (see first reference below).

Now, if you want your object itself (whatever T is) to be able to compare against itself, it can implement the IComparable interface (see second reference below).


From: http://msdn.microsoft.com/en-us/library/8ehhxeaf(v=vs.110).aspx (IComparer<T>)

We recommend that you derive from the Comparer<T> class instead of implementing the IComparer interface, because the Comparer<T> class provides an explicit interface implementation of the IComparer.Compare method and the Default property that gets the default comparer for the object.

From: http://msdn.microsoft.com/en-us/library/cfttsh47(v=vs.110).aspx (Comparer<T>)

Derive from this class to provide a custom implementation of the IComparer<T> interface for use with collection classes such as the SortedList<TKey, TValue> and SortedDictionary<TKey, TValue> generic classes. The difference between deriving from the Comparer class and implementing the System.IComparable interface is as follows:

  • To specify how two objects should be compared by default, implement the System.IComparable interface in your class. This ensures that sort operations will use the default comparison code that you provided.
  • To define a comparer to use instead of the default comparer, derive from the Comparer class. You can then use this comparer in sort operations that take a comparer as a parameter.
myermian
  • 31,823
  • 24
  • 123
  • 215
  • _"Derive from this class"_ - which class? I take it you mean `Comparer`? –  Nov 02 '14 at 11:03
  • It's a direct quote from the MSDN page on `Comparer`, so yes. – myermian Nov 02 '14 at 11:06
  • 4
    I realise that but reading your answer it is not clear what you are talking about. I have to click the link to find out. You should start of by saying _"I recommend `Comparer Class`..."_. _[Your answer is in another castle: when is an answer not an answer?](http://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer)_ –  Nov 02 '14 at 11:09
0

From this article on MSDN:

We recommend that you derive from the Comparer class instead of implementing the IComparer interface, because the Comparer class provides an explicit interface implementation of the IComparer.Compare method and the Default property that gets the default comparer for the object.

dotnetom
  • 24,551
  • 9
  • 51
  • 54