Clarification:
- 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.
- 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.
P.s.
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.
P.p.s.
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:
Post a Comment