Wednesday, August 13, 2008

Microsoft .NET Framework 2.0 - Application Development Foundation - Multicast Delegate

During my study for the 70-536 exam I came across a blog page with some questions from the exam. One of which is about multicast delegates:
Q. You need to write a multicast delegate that accepts a DateTime argument and returns a Boolean value. Which code segment should you use?
  1. public delegate int PowerDeviceOn(bool, DateTime);
  2. public delegate bool PowerDeviceOn(Object, EventErgs);
  3. public delegate void PowerDeviceOn(DateTime);
  4. public delegate bool PowerDeviceOn(DateTime);
The first observation I'd make about the available answers it that they are all missing the parameter names. They may also be missing ref and/or out keywords. Who knows. I'll assume that only the parameter names are missing.

Looking past that, I've seen comments floating round the web that "Multicast delegates must contain only methods that return void". This is misleading. It's quite possible to have a return value. See the MSDN article Multicast Delegate Internals, particularly the "Method Returns and Pass-By-Reference" section towards the end.

The issue identified in the above article is that if the "subscribers return a value, it is ambiguous which subscriber’s return value would be used". In cases such as this where the return value from each invoked method is of interest the MulticastDelegate.GetInvocationList() method can be used to manually enumerate through the list of subscribers and call them individually.

While it is possible to have return types other than void I'd be wary of doing so in practice unless there was a compelling reason.