Thursday, July 21, 2005

Events and delegates in C#, cont.

This is a continuation of a previous post.

  • The "delegate" keyword is a reference type ("class" and "interface" are also reference types).
  • The "event" keyword is a modifier (such as "public", "private", etc.), used exclusively with a delegate.
  • All delegates are multicast.
  • It is possible to use both delegates and events to implement the publish/subscribe mechanism in the Observer pattern, there are differences however.
The differences in using delegates and events in implementing publish/subscribe are the following:
  • Events cannot be fired outside the class they are defined in (delegates can), i.e. MyEvent("message") is only possible within the class MyEvent is defined.
  • Delegates can only be attached to events through += and detached through -=, e.g. MyEvent += new MyDelegate(Update).
  • Delegates can, additionally, be attached to delegates through =, but this discards those delegates that have already been added.
Conclusion: applying the "event" modifier to a delegate restricts its use and makes programming with them more safe. This is enforced at compile-time.

The Observer pattern, as defined by the Gang-Of-Four (GOF), is actually different from the publish/subscribe mechanism using delegates. The GOF pattern uses ConcreteSubject and ConcreteObserver that implement the Subject and Observer interfaces, respectively.

Why have I not seen this simple explanation of the event keyword elsewhere? Hopefully this post will save someone else the trouble of making some sense out of it.

No comments: