Thursday, October 18, 2007

DELEGATES(.NET)

Simple Delegate:

A delegate is very much like a C/C++ 'function pointer' or a 'typedef that represents the address of a function'. In C/C++, the address of a function is just a memory address. The C/C++ function pointer holds only the address of a function. This address doesn't carry any additional information, such as the number of parameters expected by the function, types of parameters it takes etc. In fact, this all makes a function pointer type unsafe. Traditionally, calling a function by its address depends on the language supporting the function pointers. And function pointers are inherently dangerous.
Delegates add a safety to the idea of traditional function pointers. The .NET framework has added the bonus of providing a type-safe mechanism called delegates. They follow a Trust-But-Verify model, with automatic verification of the signature by the compiler. Unlike function pointers however, delegates are object-oriented, type-safe, and secured. In short, a delegate is a data structure that refers to a static method or to an object instance, and an instance method of that object. When the delegate references an instance method, it stores not only a reference to the method entry point, but also a reference to the object instance for which to invoke the method.

Multicast Delegates:

Coming to multicast delegates, these are delegates which are capable of pointing to multiple functions of the same signature. The System.Delegate type maintains a linked list that is used to hold the references to the functions to be invoked by the delegate. This linked list is called as the Invocation List. The delegate class provides a shared member function called Combine(), which adds a reference of specified function to the invocation list.