The C runtime’s qsort function takes a pointer to a callback function to sort elements within an array. In Windows, callback functions are required for window procedures, hook procedures, asyn- chronous procedure calls, and more. In the .NET Framework, callback methods are used for a whole slew of things. For example, you can register callback methods to get a variety of notifications such as
unhandled exceptions, window state changes, menu item selections, file system changes, form control
events, and completed asynchronous operations.
In unmanaged C/C++, the address of a non-member function is just a memory address. This address doesn’t carry any additional information such as the number of parameters the function expects, the types of these parameters, the function’s return value type, and the function’s calling convention. In short, unmanaged C/C++ callback functions are not type-safe (although they are a very lightweight mechanism).
In the .NET Framework, callback functions are just as useful and pervasive as in unmanaged Windows programming. However, the .NET Framework provides a type-safe mechanism called delegates. I’ll start off the discussion of delegates by showing you how to use them. The following code demonstrates how to declare, create, and use delegates.
using System;
using System.Windows.Forms; using System.IO;
// Declare a delegate type; instances refer to a method that
// takes an Int32 parameter and returns void. internal delegate void Feedback(Int32 value);
public sealed class Program { public static void Main() {
using (StreamWriter sw = new StreamWriter("Status", true)) { sw.WriteLine("Item=" + value);
}
}
}
Now I’ll describe what this code is doing. At the top, notice the declaration of the internal delegate, Feedback. A delegate indicates the signature of a callback method. In this example, a Feedback del- egate identifies a method that takes one parameter (an Int32) and returns void. In a way, a delegate is very much like an unmanaged C/C++ typedef that represents the address of a function.
The Program class defines a private, static method named Counter. This method counts inte- gers from the from argument to the to argument. The Counter method also takes an fb, which is a reference to a Feedback delegate object. Counter iterates through all of the integers, and for each integer, if the fb variable is not null, the callback method (specified by the fb variable) is called.
This callback method is passed the value of the item being processed, the item number. The callback method can be designed and implemented to process each item in any manner deemed appropriate.