views:

184

answers:

2

Hi,

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.

+1  A: 

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.

xanadont
IComparer will allow me to compare two objects of the same class but I don't want to have to implement a function for each class that uses the interface ISequenced. I have expanded my question with a code sample which might give you a better idea of what I am trying to do.
link664
That's the beauty of interfaces. See edit above.
xanadont
I guess it really should be IHasSequence.
xanadont
A: 

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.

link664