The Delegates Series:
- Delegates Explained – Part 1
- Delegates Explained – Part 2
- Delegates Explained – Part 3
- Delegates Explained – Part 4 <<
In this last post in this series, I want to examine what the event keyword buys us in the subscriber model for handling events.
Consider our previous example. Recall that the notification delegate of the DvdStore class is public. Now, what would happen if we set the Notification delegate to a totally new delegate object? It would blow away the list of delegates which had previously been subscribed, is the short answer. Try it yourself and see.
static void Main(string[] args) { DvdStore theStore = new DvdStore(); theStore.notification += new NotifyDvdArrived(BroadcastArrivalOfDvdByBatSignal); theStore.notification += new NotifyDvdArrived(BroadcastArrivalOfDvdByLoudSpeaker); theStore.notification += new NotifyDvdArrived(BroadcastArrivalOfDvdBySnailMail); theStore.notification = delegate { Console.WriteLine("The Thing is not a good movie. " + "Go home and take a good hard look at your life."); }; theStore.SendOutNotification("The Thing"); // end of app Footer(); }
Line 9 is where the damage is done, publishing a sacriligious message which should be disregarded at all costs.
Now, add the event keyword on the custom delegate, keep that member public and try and set it to a new delegate object as we just did above:
public event NotifyDvdArrived notification;
Notice how … we can’t. You will get a compile error with a message along the lines of The event ‘DelegatesExplained.Program.DvdStore.notification’ can only appear on the left hand side of += or -= (except when used from within the type ‘DelegatesExplained.Program.DvdStore’
So, with encapsulation back in tact, we now have a safe way to subscribe handlers to, and removing them from, “event” delegates. This enables the delegate to be public (which it needs to be for subscribers), but protects it from being changed/written over.