I want to implement a delegate solution for Bubble sort. I have this code:
public delegate void SortHandler<T>(IList<T> t);
public static void Sort<T>(IList<T> arr, SortHandler<T> func)
{
func(arr);
}
int[] arr2 = { 10,1,2,3,4 };
CollectionHelper.Sort<int>(arr2, bubble_sort);
bubble sort function signature is:
static void bubble_sort(int[] array) {}
I get this error:
Argument ‘2’: cannot convert from ‘method group’ to ‘DelegatesAndGenerics.SortHandler
Yes – your
bubble_sortmethod requires anint[]as the parameter, whereasSortHandleronly specifiesIList<T>. You can’t create aSortHandler<int>frombubble_sort.Just because you happen to be sorting an
int[]doesn’t meanCollectionHelper.Sortis guaranteed to call the delegate with an array instead of (say) aList<int>.For example, consider this implementation:
How would you expect that to cope if you’d managed to pass in the
bubble_sortmethod as your handler?The simplest solution is to change your
bubble_sortmethod to acceptIList<int>instead of justint[].(This is a slightly strange situation though, I have to say. Usually the kind of handler you’d pass into a generic sort method would be something to compare any two elements – not to perform the actual sort itself.)