Events Cheat Sheet

How to use delegates to publish events

1.     Define a delegate

·         Compiler produces a class deriving from System.Delegate

 

delegate void NotifyDel(string data)

 

2.     Add a public field of the delegate type to the publisher

·         Insert the event keyword to encapsulate the delegate field so that subscribers cannot clear the list or directly invoke the delegate.

 

class Publisher

{

  public event NotifyDel OnNotify;

  ...

 

3.     Add a callback method to the subscriber

·         Subscriber’s callback method signature must match delegate definition.

 

class Subscriber

{

  void NotifyCallback(string data)

  {

  ...

 

4.     Add the subscriber’s callback method to the publisher’s event

·         Use += to add, or -= to remove a target method.

 

class Subscriber

{

  public Subscriber(Publisher publisher)

  {

    publisher.OnNotify += NotifyCallback;

  }

  void NotifyCallback(string data)

  { ...

 

5.     Fire the event from the publisher

·         Make sure the delegate field is not null.

 

class Publisher

{

  public event NotifyDel OnNotify;

  public void DoSomething()

  {

    if (OnNotify != null) OnNotify("interesting stuff");

  ...