Why delegates?

In the past, you could pass a function pointer, cast as an int, and it was up to the function being called to know what type of function pointer was passed. This improved somewhat with later versions of C where the return type of function, number of arguments, and argument type could all be specified. The problem is that it was not type-safe. One example that is used frequently is qsort. This function was passed a void pointer to what was to be sorted, the number of elements to be sorted, the size of the elements, and a comparison function. The call to qsort when you are sorting an array of int might look like this:

int a[100]
// Initialize array a
. . .
qsort((void *)a, 100, sizeof(int), compare);

The comparison routine would ...

Get .NET Common Language Runtime Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.