R – Using reflection for generically typed delegate and interfaces

netreflectionvb.net

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.

Best Answer

Implement an IComparer. Everything you need is here.

Edit: Oh, I see what the rub is. All the classes that have the Sequence property must implement an interface to be comparable. E.g. use IHaveSequence and do an IComparer< IHaveSequence>. IHaveSequence's definition should be obvious.