Friday 16 October 2009

A reminder about delegates

A delegate is a reference type used to encapsulate a method with a specific signature and return type. You can encapsulate any matching method in that delegate.

From MSDN documentation:

“A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value…

…Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own delegated method.

This ability to refer to a method as a parameter makes delegates ideal for defining callback methods.”

The documentation goes on to state that delegates have the following properties (and others):

  • Delegates are similar to C++ function pointers, but are type safe.
  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.

Delegate creation syntax:

// define the delegate
public delegate void MyDelegate(object sender, EventArgs e);

// The public member variable myDelegate is an instance of a MyDelegate delegate
public MyDelegate myDelegate;

// assign method SomeMethod to myDelegate
myDelegate = SomeMethod(object myObject, new EventArgs());

Note that this removes any previously assigned methods from the delegate and assigns the new one. You can use an alternative syntax to add more than one method to a delegate. You can then execute all methods in one delegate call:

public delegate  void MyDelegate(object sender, EventArgs e);
public MyDelegate myDelegate;
 
myDelegate += SomeMethod(object myObject, new EventArgs()); 
myDelegate += SomeOtherMethod(object myObject, new EventArgs());
 
//Call both methods
myDelegate(obj, args);

Events

The event keyword restricts how delegates are used. Events are delegates that:

  • Can only be registered with += and not with the assignment operator (=)
  • Can only be called by methods of the class that defines the event
public delegate  void MyDelegate(object sender, EventArgs e);
public event MyDelegate myDelegate;
 
myDelegate += SomeMethod(object myObject, new EventArgs()); 
myDelegate += SomeOtherMethod(object myObject, new EventArgs());

// Compilation error here! Can't asign to an event.
myDelegate = YetAnotherMethod(object myObject, new EventArgs());
 
//Call both methods
myDelegate(obj, args);
Friday 16 October 2009