Difference between events and delegates and its respective applications [closed]

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).

Leave a Comment