Its an object which allows you to reference a method.Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.
Actualy its like a pointer in C or C++ but delegate is not a pointer in C#, its an object so we can create the insatnce of delegate by using 'new' keyword. And also unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.
An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.
NOTE : Delegates run under the caller's security permissions, not the declarer's permissions.
Why?
- Giving you maximum flexibility to implement any functionality you want at runtime.
- The association between delegate and methods referenced by delegate is established in runtime - so, you get flexibility here.
- Multi-cast: That's to associate a few methods/functions to ONE delegate. Invoking one delegate fires off ALL methods referenced by that one delegate all at once.
- The use of delegates promotes good separation of functionality between the business layer/anyother layer and the client code. The client code has no knowledge of how logics works in other layer.
Delegates are useful when:
- A single method is being called.
- A class may want to have multiple implementations of the method specification.
- It is desirable to allow using a static method to implement the specification.
- An event-like design pattern is desired.
- The caller has no need to know or obtain the object that the method is defined on.
- The provider of the implementation wants to "hand out" the implementation of the specification to only a few select components.
- Easy composition is desired.
- The specification defines a set of related methods that will be called.
- A class typically implements the specification only once.
- The caller of the interface wants to cast to or from the interface type to obtain other interfaces or classes.
- Declaring a delegate
public delegate void ProcessBookDelegate(Book book);
Each delegate type describes the number and types of the arguments, and the type of the return value of methods that it can encapsulate.Whenever a new set of argument types or return value type is needed, a new delegate type must be declared.
2. Instantiating a delegate
bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(PrintTitle));
Note that once a delegate is created, the method it is associated with never changes — delegate objects are immutable.
3. Calling a delegate
delegateObject(argument)
Reference:
http://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx