I was looking at
IComparer(Of T)[
^] when I found:
"We recommend that you derive from the Comparer(Of T) class instead of implementing the IComparer(Of T) interface, because the Comparer(Of T) class provides an explicit interface implementation of the IComparer.Compare method and the Default property that gets the default comparer for the object."
Something similar is recommended for
IEqualityComparer(Of T)[
^].
Now my question is: Why should I derive rather than Implement?
I do not find the MSDN articles clear enough at this point.
Maybe someone could enlighten me? :)
Edit:
I have currently implemented my IComparer like this:
Public Class OrderPriceComparer
Implements IComparer(Of IOrder)
Public Function Compare(ByVal x As IOrder, ByVal y As IOrder) As Integer Implements System.Collections.Generic.IComparer(Of IOrder).Compare
Dim greater As Integer
If x.CalculatePrice < y.CalculatePrice Then
greater = -1
ElseIf x.CalculatePrice = y.CalculatePrice Then
greater = 0
Else
greater = 1
End If
Return greater
End Function
End Class
It gets called like:
Me.Orders.Sort(New OrderPriceComparer)
For a default ordering of my orders I have my OrderClass which Implements IComparable(Of IOrder).
The implementation looks like this:
Public Function CompareTo(ByVal other As IOrder) As Integer Implements System.IComparable(Of IOrder).CompareTo
Dim greater As Integer
If other.ID > Me.ID Then
greater = -1
ElseIf other.ID = Me.ID Then
Throw New Exception("An order cannot be compared to itself.")
Else
greater = 1
End If
Return greater
End Function
So I can now also call List(Of IOrder).Sort or pass it an optional IComparer to sort on anything different than ID.
Although I do have to make a new Class for every Property I want to sort on.
PS. I could not simply return the difference between x.CalculatePrice and y.CalculatePrice or Me.ID and other.ID because they are not Integers and I want to be safe for rounding differences and OutOfRangeException ;)