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?
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 theComparer<T>
class provides an explicit interface implementation of theIComparer.Compare
method and theDefault
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 theSortedList<TKey, TValue>
andSortedDictionary<TKey, TValue>
generic classes. The difference between deriving from the Comparer class and implementing theSystem.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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With