I thought I would write a small series of articles on delegates for students. I can recall as a student, how I learnt many things from blog posts of enthusiastic developers.
The Delegates Series:
- Delegates Explained – Part 1 <<
- Delegates Explained – Part 2
- Delegates Explained – Part 3
- Delegates Explained – Part 4
I will firstly explain what delegates are. Then I shall go through various code examples to show the syntax for their use. The series will start off with the basics and evolve the concept of delegates in bite-size chucks.
What is a Delegate?
From a (very good) textbook*:
a delegate is a type-safe object that points to another method (or possibly a list of methods) in the application, which can be invoked at a later time. Specifically speaking, a delegate object maintains three important pieces of information:
- The address of the method on which it makes calls
- The arguments (if any) of this method
- The return value (if any) of this method
What this gives us is a type-safe way to implement callbacks.
I think of callbacks like this (using humans as an analogy): I say to you, “Here, take this phone number. Now go off and do a task and when you are done, ring this number.” Or if we are talking asynchronous, “Here, take this email address. Now go off and do a task and when you are done, send an email to that address.” The act of ringing that number, or sendng that email, is the callback.
Ok. We’re back.
An Example – The DVD Store Notification Subscription
I’ll go through a simple example in this post. There is a DVD store which we want to tell us when a new DVD arrives. So, we are going to subscribe for that. The DVD store says to the world at large, “If you provide us with a notification method that adheres to a certain specification, then we will notify you of new releases using that method.” In this case, the specification for that method is the delegate called NotifyDvdArrived.
public delegate void NotifyDvdArrived(string title);
This requires the method to have a void return type and take a single string parameter. Lets take a look at the DVDStore class:
public class DvdStore
{
private NotifyDvdArrived notification;
public DvdStore()
{
// default constructor
}
public void SubscribeMeForNotifications(NotifyDvdArrived notificationMethod)
{
notification = new NotifyDvdArrived(notificationMethod);
}
public void SendOutNotification(string titleOfDvd)
{
notification.Invoke(titleOfDvd);
}
}
The SubscribeMeForNotifications method is the one by which we can tell the DVD Store that we want to receive notifications. It takes a NotifyDvdArrived delegate as a parameter which enables us to tell them how we want to receive that notification. As the name suggests, the SendOutNotification method is what the DVD store uses to broadcast its notifications. Any object that has subscribed to receive notifications will do so in the way in which it has specified to do so, when it subscribed for the notification (I will show how more than 1 object can subscribe in a future post).
The contents of the Main method are quite simple:
static void Main(string[] args)
{
DvdStore theStore = new DvdStore();
theStore.SubscribeMeForNotifications(new NotifyDvdArrived(BroadcastArrivalOfDvd));
theStore.SendOutNotification("The Thing");
Footer();
}
We (the Main method) go to a DVD Store, subscribe for notifications, and we do so supplying the BroadcastArrivalOfDvd method, which is:
private static void BroadcastArrivalOfDvd(string titleOfDvd)
{
Console.WriteLine("The Dvd called {0} has arrived.", titleOfDvd);
}
Looking back at the SendOutNotification method, it calls the Invoke method of the delegate object which calls (calls back) the BroadcastArrivalOfDvd method which we subscribed with, passing it the string parameter which is passed to SendOutNotification.
What’s the Benefit?
Delegates allow us to decouple, which is the first step to a scalable, maintainable architecture. This benefit will probably be lost on you students, until you enter the world of enterprise development. Translation – just trust me, it’s a good thing.
In my next Delegates post, I will take the example a little further to unlock a few more features that you need to know about delegates. The source code for this article can be
downloaded here:
*Andrew Troelsen’s Pro C# 2008 and the .NET 3.5 Platform at p.341
