I have a bunch of classes that each have a property called Sequence. This property is implemented from an interface called ISequenced. For this example lets call one of these classes A.
When I have a List(of A), I want to be able to sort them using the standard List.Sort(addressof delegate) where the delegate is a standard function that takes in two ISequenced objects and compares their sequence numbers and returns a boolean flag, rather than declaring a function for each individual class that implements ISequenced.
E.g.
Dim li as List(of A) = GetValues()
li.Sort(addressof SortBySeq)
...
Public Function SortBySeq(ByVal ob1 as ISequenced, ByVal ob2 as ISequenced) as Boolean
return ob1.Sequence.CompareTo(ob2.Sequence)
End If
EDIT: Using the above gives me the following error:
“Overload resolution failed because no
accessible ‘Sort’ can be called with
these arguments:
‘Public Sub Sort(comparison As System.Comparison(Of A))’: Option
Strict On does not allow narrowing in
implicit type conversions between
method ‘Public Function SortBySeq(ob1
As ISequenced, ob2 As ISequenced) As
Integer’ and delegate ‘Delegate
Function Comparison(Of A)(x As A, y As
A) As Integer’.
‘Public Sub Sort(comparer As System.Collections.Generic.IComparer(Of
A))’: ‘AddressOf’ expression cannot be
converted to
‘System.Collections.Generic.IComparer(Of
A)’ because
‘System.Collections.Generic.IComparer(Of
A)’ is not a delegate type.”
How would I declare the function in order to do this (if it is even possible in VB.NET?
Thanks,
Dane.
Didn’t need to implement IComparer in the end as I was only comparing decimals. Turns out that .NET 3.5 added at least some covariance abilities with delegates so I’ve upgraded to that and the example I gave above seems to work fine.