Rarely working with certain aspects of the .NET Framework or even the syntactical sugar can leave one confused, spending time re-learning and remembering. So to my stumblings in Delegates

There are 4 main areas of Delegates in principal:

  1. Generic – declare, instantiate and call
  2. Combining Delegates
  3. Events
  4. Multi-cast Delegates

Generic:

Basically a delegate is a “function pointer”. That is, it’s an address space that points to a memory location that contains a “function”. Even more simpler, it’s a placeholder for any function that has a matching type and arguments. Even simpler, it is a glove that can fit any hand, but it can only fit a hand.

For example:

// Declaration <access-modifier> <return-type> <name> (<anonymous function matching arguments>)
public delegate void ProcessBookDelegate(Book book);

// Explanation:
Here we have declared a “delegate” called ProcessBookDelegate, who will “refer” to any function as long as it’s arguments support two things
a) A matching return type
b) Matching arguments
Don’t worry it will all make sense just now.

So if we had a the method: (assume lstBooks is an ArrayList that contains a list of books to process)[ ProcessBooks is a member of BookManager ]

public void ProcessBooks(ProcessBookDelegate processBook)
{
foreach(Book book in lstBooks)
{
processBook(book);
}
}

// Explanation:

Now we have created a method that takes in a “Method/Function” as an argument that matches the “delegate” return and argument type. This passed in method will then be used to process a book.
Now let’s create two methods we can use interchangeably to process a book.

static void PrintTitle(Book b)
{
Console.WriteLine(" {0} ", b.Title);
}

static void AddBooks(Book b)
{
addnewbook.Title(b.Title);
addnewbook.Isbn(b.Isbn);
addnewbook.Author(b.Author)
}

// Explanation:
Now these two methods are of the same return type and have the same arguments. These then both qualify to be used by my delegate to point to either method.
Thus for example, I could pass in PrintTitle and that’s what it would do, Print the Title of the Book.
Or I could pass in AddBooks and it would use an “addnewbook” to add information from the Book object into my datasource or database.

Code as follows:
bm.ProcessBooks(new ProcessBookDelegate(PrintTitle));
bm.ProcessBooks(new ProcessBookDelegate(AddBooks));

Thus a delegate is a function pointer or a type-safe method for using multiple functions. Hopefully (if I’m not to lazy, will complete the next in the series in and around events)

Don't be shellfish...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrEmail this to someone

2 thoughts on “”

Leave a Reply