Difference between events and delegates and its respective applications

Sasha picture Sasha · Feb 19, 2009 · Viewed 77.3k times · Source

I don't see advantages of using events over delegates, other than being syntactical sugar. Perhaps I am misunderstanding, but it seems that event is just a placeholder for delegate.

Would you explain to me the differences and when to use which? What are the advantages and disadvantages? Our code is heavily rooted with events, and I want to get to the bottom of it.

When would you use delegates over events and vice versa? Please state your real world experience with both, say in the production code.

Answer

Peter Wone picture Peter Wone · Feb 19, 2009

The keyword event is a scope modifier for multicast delegates. Practical differences between this and just declaring a multicast delegate are as follows:

  • You can use event in an interface.
  • Invocation access to the multicast delegate is limited to the declaring class. The behaviour is as though the delegate were private for invocation. For the purposes of assignment, access is as specified by an explicit access modifier (eg public event).

As a matter of interest, you can apply + and - to multicast delegates, and this is the basis of the += and -= syntax for the combination assignment of delegates to events. These three snippets are equivalent:

B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = B + C;

Sample two, illustrating both direct assignment and combination assignment.

B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = B;
A += C;

Sample three: more familiar syntax. You are probably acquainted with the assignment of null to remove all handlers.

B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = null;
A += B;
A += C;

Like properties, events have a full syntax that no-one ever uses. This:

class myExample 
{
  internal EventHandler eh;

  public event EventHandler OnSubmit 
  { 
    add 
    {
      eh = Delegate.Combine(eh, value) as EventHandler;
    }
    remove
    {
      eh = Delegate.Remove(eh, value) as EventHandler;
    }
  }

  ...
}

...does exactly the same as this:

class myExample 
{
  public event EventHandler OnSubmit;
}

The add and remove methods are more conspicuous in the rather stilted syntax that VB.NET uses (no operator overloads).