Tuesday, September 11, 2012

Why do we need events when we have delegates?

Ok I understand that the answer to this question is pretty simple. But, I have seen many people faltering in interviews when asked this question.

We have a class with a public delegate and a property which exposes an instance of the delegate.

Code Snippet
  1. public class Temp
  2. {
  3.     public delegate void TestEventDelegate(string input);
  4.  
  5.     public TestEventDelegate TestEvent { get; set; }
  6.  
  7.     private void RaiseTestEvent(string arg)
  8.     {
  9.         TestEvent(arg);
  10.     }
  11. }

Now TestEvent is a multicast delegate. We can create an instance of the class Temp and add our method to TestEvent

Code Snippet
  1. var t = new Temp();
  2. t.TestEvent += input => Console.WriteLine("{0} received", input);

Similarly some other class might create another instance of Temp and add its own method to TestEvent

Code Snippet
  1. var p = new Temp();
  2. p.TestEvent += input => Console.WriteLine("Hell0 {0}", input);

And when Temp calls RaiseTestEvent method, all methods added to the multicast delegate TestEvent will be called. Now think about this for a moment. Doesn’t an event do exactly the same thing? Subscribers add their event handlers which get called when the event is raised. So, why do we need events and their fancy syntax? For that you should know that events can be raised only by the class which defines it, unlike the public delegate which can be called from outside the class by using the instance of the class in which it is defined. This is the main functionality of an event, where the class that defines it controls when an event needs to be raised.

2 comments:

  1. I second what you have written. But the question remains why is it so?
    Let me try to address it.

    Events are computer science constructs.
    Delegates are constructs of C# language.

    And in C# events are implemented using delegates.

    This (http://blog.monstuff.com/archives/000040.html) help to bring in more understanding to what you have written.

    ReplyDelete
  2. Hi N!lesh,

    Yeah, hence I say that 'the class that defines it controls when an event needs to be raised.'
    Thanks for the link.

    ReplyDelete