Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we extend Comparer<T> or implement IComparer<T>

Tags:

c#

icomparer

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?

like image 438
Sebastian Widz Avatar asked Nov 02 '14 10:11

Sebastian Widz


2 Answers

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.
like image 166
myermian Avatar answered Oct 02 '22 23:10

myermian


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.

like image 43
dotnetom Avatar answered Oct 02 '22 23:10

dotnetom