Using Delegates and Events
Delegates are object-oriented function pointers that safely encapsulate a method. A delegate must be of type delegate, define a return type and optionally a parameter list, like this:
public delegate void ImDelegate(int x, int y);
This delegate then can point to any methods which returns void and takes two integer values as parameters. To try our new delegate add the following code:
public static void Add(int x, int x)
ImDelegate handler = Add;
This code creates a method, and then use it by calling the delegate. Delegates can be passed into methods, in this way creating a callback method. More info about this is on MSDN.
You can invoke multiple methods with a single delegate, the only constraint is that the signatures must match. To do so, simply use the following syntax:
ImDelegate handler = method1;
handler += method2;
This code will call both method1 and method2. You can also combine the invocation lists of multiple delegates by using the delegate.Combine method.
Events are messages sent by objects that signals that something has happened. The trigger of an event can be user interaction, programming logic, etc. To define an event, you’ll need a delegate. In my example, I’ll use the traditional EventHandler delegate, which declares a void that accepts an object, as the sender and an empty EventArgs class:
public event EventHandler myEvent;
This event can be rigged by the following code:
myEvent += new EventHandler(myVoidMethod);
if(myEvent != null)
myEvent(this, new EventArgs());
public void myVoidMethod(object sender, EventArgs e)
//execution code goes here.
Before you call an event, you’ll always need to check it for a null value, and only call it if it has value.
Event handler delegates traditionally returns the source of an event as an object, and an instance of the EventArgs (or derived) class. You can store any event-related data in this class. The creating of an EventArgs class is very straightforward, visit MSDN if you’re stuck with it.