Delegates and events
A callback is a function (or more generally, any executable code) that is passed as a parameter to another function in order to be called immediately (synchronous callbacks) or at a later time (asynchronous callbacks). Operating systems (such as Windows) use callbacks extensively to allow applications to respond to events such as mouse events or key presses. Another typical example for callbacks is general purpose algorithms that use callbacks for processing elements from a collection, such as comparing them in order to sort them or filter them out.
In languages such as C and C++, a callback is simply a function pointer (that is, the address of a function). However, in .NET, callbacks are strongly-typed objects that hold not only the reference to one or more methods but also the information about their parameters and return type. In .NET and C#, callbacks are represented by delegates.
Delegates
A delegate is defined using the delegate
keyword. The declaration...