Skip to content

Delegates and Events

by Alex Peck on July 5th, 2009

Delegates

A delegate is a reference type that encapsulates a method, and may be used rather like a function pointer in C/C++. Unlike function pointers, delegates are object-oriented and type-safe. The term delegate is used to describe both delegate types and instances.

When you declare a delegate type, you define the method signature for instances of the type. Delegate instances always refer to methods. The following somewhat contrived example illustrates type and instance declaration, and delegate invocation.

public delegate void DelegateType();
 
public class DelegateHost
{
    public void InstanceMethod()
    {
        Console.WriteLine("Instance method."); 
    }
 
    public static void StaticMethod()
    {
        Console.WriteLine("Static method."); 
    }
}
 
public class Test
{
    private DelegateType delegateInstance;
 
    public void DoTest()
    {
        delegateInstance = new DelegateType(DelegateHost.StaticMethod);
        delegateInstance();
 
        DelegateHost host = new DelegateHost();
        delegateInstance = new DelegateType(host.InstanceMethod);
        delegateInstance();
    }
}

As well as having single action delegate instances, you can also create multicast delegates. Delegate instances can be combined and removed from one another. Delegate instances are immutable.

Events

I originally understood events to be a multicast form of delegates. Given that you can create multicast delegates, what then is the purpose of event?

The event keyword is effectively a modifier for a delegate declaration. Events may be distinguished from raw delegates as follows:

  • An event can be included in an interface declaration, whereas a delegate field cannot
  • An event can only be invoked from within the class that declared it
  • Events have a pair of customisable accessors (add and remove), in this regard they are very similar to properties
  • Within the .NET framework, an event delegate signature must be of the form void Event(object sender, EventArgs e)
No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS