views:

37

answers:

2

Hi, 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

A: 

I think the issue is that your int[] isn't an IList. If you change your SortHandler delegate like so:

public delegate void SortHandler<T>(IEnumerable<T> t);

you should be able to use arrays, lists, or whatever you want.

ckramer
Doesn't int[] implements the generic interface IList<int>?
Guy Z
That will have exactly the same problem. `int[]` *does* implement `IList<int>`, but you still can't use a method which will *only* accept an `int[]` for a delegate which is meant to take *any* `IList<int>`.
Jon Skeet
When your right, your right. Teach me to not pay attention. Can I down-vote myself?
ckramer
+3  A: 

Yes - your bubble_sort method requires an int[] as the parameter, whereas SortHandler only specifies IList<T>. You can't create a SortHandler<int> from bubble_sort.

Just because you happen to be sorting an int[] doesn't mean CollectionHelper.Sort is guaranteed to call the delegate with an array instead of (say) a List<int>.

For example, consider this implementation:

public void Sort<T>(T[] array, SortHandler<T> handler)
{
    List<T> list = new List<T>(array);
    handler(list);
}

How would you expect that to cope if you'd managed to pass in the bubble_sort method as your handler?

The simplest solution is to change your bubble_sort method to accept IList<int> instead of just int[].

(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.)

Jon Skeet