When I read my e-mail this morning I saw that I had a reply to my post about the Action<T> delegate and the ForEach(…) method (look at the comment from Mark Richards). The implementation example he gave showed an Action<T> delegate being exposed as a property on a command object.

It got me thinking about delegates and how they are generally used by developers today in their software. Off the top of my head I came up with this short list of places where delegates are used regularly (note the emphasis).

  • Wiring up events and implementing the eventing pattern.
  • Writing code to marshal from one thread to another in Windows Forms programming.

I’m sure there are a few others, but these are the main ones that I come across. To think of more creative uses of delegates we might need to look further a field. For example, take a look at the Button class which is part of Avalon (upcoming UI framework and application model for Windows).

The Button class derives from the Control class which exposes a number of properties like Height and Width. But if you look more closely at the documentation for those properties you see that they have a related property, in the case of Width, there is also a WidthProperty property – confused?

When I first saw this I thought it was an odd naming convention, but what the Avalon team have done is very clever. Rather than going for a static property model they allow developers to specify that a properties value can change, which can be really useful for things like animation. They do this by defining the property as taking a DependencyProperty object.

This object exposes the underlying value but also has some registration methods which allow other bits of code to listen for changes in the value – driven by some kind of external influence such as a tick of a clock for example. It is possible to simulate a similar mechanism using delegates as properties – this should look A LOT like events, but can you imagine the possibilities if you could do this with every property.

ComputeFormLoad

Here I’ve told the derived button class (ComputeButton) that I want it to choose a random colour every time it paints, and I’ve supplied the logic via the Generic Compute delegate.

GenericCompute

Its a very simple delegate (note – I made it up myself – this is all theorhetical), and you apply it to a class like this:

ComputeButton

You can see here that every time someone asks for the back colour on the button it will call the code that is pointed to via the generic Compute delegate. By way of demonstration, if I added that button to a form and moved my mouse over the top of it, the colour would flicker randomly.

ComputeRunning

This is a fairly primitive example, but I hope it illustrates the point that with delegates your code can become much more dynamic, whether thats a good thing and whether this code is easy to maintain is a completely different question. Anyway – you can download the code for this sample here.