Friday, May 08, 2009

C# Delegate put in use

A deeper look into delegate use just blown me away. It make the code so modular and clean that the old way of passing in object and dependencies changes issues is resolved.

What is delegate?
Delegate is a type that can associate with any method with compatible signature. It's like pointer to function.

Delegate declaration and usage

1. Declare: delegate signature(parameters)
public delegate void ProcessBookDelegate(Book book);

2. Instantiate delegate instance and associate with handler method
bookDB.ProcessPaperbackBooks(PrintTitle);
bookDB.ProcessPaperbackBooks(totaller.AddBookToTotal);

3. Subscriber method and Invoke: SubscriberMethod(delegate name)
public void ProcessPaperbackBooks(ProcessBookDelegate processBook)
{
processBook(mybook);
}
The above example in details. What the code achieved is call different method via a common method (depending on the which method is associated with the delegate)
http://msdn.microsoft.com/en-us/library/ms173176.aspx


What are the type of delegates?
  1. Covariance - delegates can be used with methods that have return types that are derived from the return type in the delegate signature. In other words, the delegate signature can returns type of base class or inherited type.
  2. Contravariance - subscriber can use the same delegate to handle different method as long as the delegate signature base type is the same. A muticasting example, Base class - Vehicle has children class Truck and Car. Subscriber class - .OnTheMove += Truck.Move + Car.Move.
Examples:

1. Object type is passed in at run-time.
public delegate void Del(T item);
public void Notify(int i) { }

Del<int> d2 = Notify;

Further reading:
MSDN Delegate reference guide
http://msdn.microsoft.com/en-us/library/ms173174.aspx

Simple Direct Examples
http://www.akadia.com/services/dotnet_delegates_and_events.html

No comments: