Friday 3 September 2010

When to use delegates

I was recently asked to describe delegates and when they should be used. As is often the case with simple questions like this trying to explain what I know got me in a bit of a knot, so…

Read A reminder about delegates first!

MSDN has an interesting little article about When to Use Delegates Instead of Interfaces. This draws a parallel between interfaces and delegates that I hadn’t considered before. The article states:

“Both delegates and interfaces enable a class designer to separate type declarations and implementation. A given interface can be inherited and implemented by any class or struct. A delegate can be created for a method on any class, as long as the method fits the method signature for the delegate. An interface reference or a delegate can be used by an object that has no knowledge of the class that implements the interface or delegate method.”

It goes on to suggest that a delegate should be used when:

  • An eventing design pattern is used.
  • It is desirable to encapsulate a static method.
  • The caller has no need to access other properties, methods, or interfaces on the object implementing the method.
  • Easy composition is desired.
  • A class may need more than one implementation of the method.

It also occurred to me that delegates could be used to implement the coroutine pattern by exposing an IEnumerable of Action types.

The MSDN article goes on to suggest that Interfaces should be used when:

  • There is a group of related methods that may be called.
  • A class only needs one implementation of the method.
  • The class using the interface will want to cast that interface to other interface or class types.
  • The method being implemented is linked to the type or identity of the class: for example, comparison methods.
Friday 3 September 2010