0

MS documentation notes that it is better to derive from Comparer class rather than implement class that implements IComparer<T> interface.

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.

So why derive from Comparer in order to create custom comparator ?

newprint
  • 6,936
  • 13
  • 67
  • 109
  • 3
    The answer is in the quote... If you don't need the non-generic `IComparer` implementation, then don't follow the advice. Don't forget, recommendations, guidelines, and advice are all optional. – Adam Houldsworth Apr 01 '14 at 10:10
  • 1
    -1 because your claim that it gives no reason is simply not true. –  Apr 01 '14 at 10:11
  • 1
    The point about the `Default` property is simply incorrect; that will not ever return custom subclass – Marc Gravell Apr 01 '14 at 10:11
  • @MarcGravell I think it's correct, but not what you think it means. A custom derived class might use `Default` as part of its implementation. –  Apr 01 '14 at 10:12
  • 1
    @hvd yes, but since `Default` is public, a custom non-derived class might **equally** use `Default` as part of its implementation – Marc Gravell Apr 01 '14 at 10:13
  • @MarcGravell Sure, but it would then need to be prefixed by `Comparer.`. I'm reading the quote as saying `Default` is easier to access. –  Apr 01 '14 at 10:14
  • but @marc documentation doesn't claims `Default` property will return custom subclass ever. but it is confusing enough. – Sriram Sakthivel Apr 01 '14 at 10:15
  • 1
    @hvd the chances of a custom comparer needing to access the default comparer **of the same type** are virtually nil. I can see how it might want to access the default comparer of *encapsulated types* (i.e. types that the `T` in question has as properties), but to do that would require the `Comparer` prefix. I geuninely don't see that this MS guidance adds anything of any use. – Marc Gravell Apr 01 '14 at 10:15
  • 1
    @MarcGravell I can think of one (but only one) example: a `ReverseComparer` class that returns positive when the default comparer returns negative, and vice versa. –  Apr 01 '14 at 10:16
  • @hvd I'll grant you that one, but frankly - it isn't exactly a huge saving! – Marc Gravell Apr 01 '14 at 10:19

1 Answers1

2

The main benefit is that this makes your comparer implement the non-generic IComparer interface for free, which can be useful when interoping with legacy APIs or if you want to be able to store a collection of comparers for different types.

Check out this related question

Community
  • 1
  • 1
ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152