Events/Delegates In Java or C#

c#, delegates, event-handling, java

Solution

(This is all from a C# perspective.)

I have an article about the differences between events and delegates. That covers everything mentioned below in a lot more detail.

Basically I like to think of an event as being like a property - it's a pair of methods, that's all. Instead of get/set, an event has add/remove - meaning "add this event handler" and "remove this event handler". At the core, that's all an event is.

C# also has field-like events which are a shortcut:

 public event EventHandler Foo;

declares both a field and an event, with a nearly trivial add/remove implementation. Within the class, referring to `Foo` refers to the field. Outside the class, referring to `Foo` refers to the event.

The basic idea is that an event allows other code to subscribe to and unsubscribe from it, by passing in a delegate (the event handler). Usually, subscription is implemented by creating a new multicast delegate containing the previous list of event handlers and the new one. So if you're storing the event handlers in a field called `myEventHandlers`, the subscription implementation might be:

myEventHandlers += value;

Similarly unsubscription usually involves creating a new multicast delegate without the specified handler:

myEventHandlers -= value;

Then when you want to raise/fire the event, you just call that multicast delegate - usually with a nullity check to avoid an exception being thrown if no-one has subscribed:

EventHandler handler = myEventHandlers;
if (handler != null)
{
    // You could pass in a different "sender" and "args" of course
    handler(this, EventArgs.Empty);
}

Using events, the subscribers don't know about each other, and can't raise the event themselves (usually). In other words, it's a pattern of encapsulation, which has been given status within both the language and the platform.

Problem

I've been trying to learn about events/delegates, but am confused about the relationship between the two. I know that delegates allow you to invoke different functions without needing to know what particular function is being invoked. (eg: a graphing function needs to accept inputs that are different functions to be graphed). But I don't see how delegates are used in Events. Can someone construct a simple example (in pseudocode or C# or Java) that illustrates the workings of Delegates as related to Events? Thanks!

Original source