Events and delegates and its difference in dotnet application

+1 vote
asked Jul 14, 2013 in C#.NET by Yadav

I think the most difficult topic to understand in .NET is Events and Delegates. I have read lot of articles to understand what are events and delegates. Every article explained how to declare and use the delegate also it says delegates are function pointers. But somehow I am not getting the clear picture of what the real purpose of having both events and delegates? Because we can use the delegate itself to call multiple method or handlers. When a delegate itself can be used for calling the attached methods, why do we really need events?

Share

1 Answer

+1 vote
answered Jul 15, 2013 by Aadhira (1,213 points)
selected Jul 15, 2013 by administrator
 
Best answer

Events and Delegates:

Events and delegates are most important concept in dotnet programming because, everywhere in dotnet you see that Microsoft has used it. Most us would think events and delegates or simple to understand. Actually, it is if you understand how it works? Otherwise it will confuse.

Before you read further, I would strongly recommend you read and understand delegates to know how and why we use it in dotnet applications.

private void button1_Click(object sender, EventArgs e)
{
}

We all might have seen the above line of code if we have worked on dotnet winforms application. Its is very common. What is it really? It is an Event handler. There is an event called "Click" in button class. Whenever a user clicks the Button in our winforms, that button will raise "Click" event. Then the above method will be called.

But how does the winform know that, it should call this button1Click method when the user click the button1? Unless we inform the button class, it does not know. You can say that, you do not see anywhere you have informed the winforms to call this button1Click event handler. Actually you did. When you double clicked the button from the designer file, dotnet framework did that for you. Here is the code which was created by dotnet when you double clicked the button1 from designer.

this.button1.Click += new System.EventHandler(this.button1_Click);

But, where is code? This code is under the designer.cs file. For each and every winform screen you will have a designer file. Once you open that file, you will see a collapsed region "Windows Form Designer generated code". If you expand that, you will see this line.

Okay, what is the below line mean?

this.button1.Click += new System.EventHandler(this.button1_Click);

This line of code has multiple information.
Which Event handler it suppose to call?
this.button1_Click

What should be signature of that event handler?
Event handler signature must match the signature of the delegate. So, it is basically telling which delegate is used for this event handler.
new System.EventHandler

For which event, the event handler should be called?
this.button1.Click

This is how the winform knows when to call button1_Click event handler.

If you have read the article understand delegate link, you may ask me why we need "Events" at all, if we can use the delegate itself to add multiple methods into the delegate and all of them can be invoked. The what is the purpose of using events.

I have one data collection. And data processed in another class "DataProcessor". When the data get process, I get the status update in two different method which are in 2 different classes. I have passed the DataProcessor class instance to the constructor of each Subscriber classes. Then each class will attach its handlers to the delegate.

public class Program
{
    static DataProcessor dataProcessor = null;

    static void Main(string[] args)
    {
        dataProcessor = new DataProcessor();
        Subscriber1 subscriber1 = new Subscriber1(dataProcessor);
        Subscriber2 subscriber2 = new Subscriber2(dataProcessor);
        dataProcessor.Process(new List<int> { 1, 2, 3, 4 });
        Console.Read();
    }
}

public class Subscriber1
{
    DataProcessor _dataProcessor = null;
    public Subscriber1(DataProcessor dataProcessor)
    {
        _dataProcessor = dataProcessor;
        _dataProcessor.updateHandledBy += DataProcessUpdateHandler;
    }
    private void DataProcessUpdateHandler(int index)
    {
        Console.WriteLine("Update received by Subscriber1 for Item " + index.ToString());
    }
}

public class Subscriber2
{
    DataProcessor _dataProcessor = null;
    public Subscriber2(DataProcessor dataProcessor)
    {
        _dataProcessor = dataProcessor;
        _dataProcessor.updateHandledBy += DataProcessUpdateHandler;
    }
    private void DataProcessUpdateHandler(int index)
    {
        Console.WriteLine("Update received by Subscriber2 for Item " + index.ToString());
        **_dataProcessor.updateHandledBy = null;**
    }
}

public class DataProcessor
{
    public DataProcessUpdateHandler updateHandledBy = null;

    public void Process(List<int> dataCollection)
    {
        for (int i = 0; i < dataCollection.Count; i++ )
        {
            //Long running code
            if (updateHandledBy != null)
                updateHandledBy(i);
        }
    }
}

But the evil in the above example is the bold line

_dataProcessor.updateHandledBy = null;

What will happen, if anyone of the subscriber made the delegate as null when it is being used by multiple listeners.

Once the delegate become null, everyone will be removed from the listeners list. So, no one going to receive the update from "Process" method. The example we have used may not be a critical scenario. But, what will happen if we are using some third party service and the same service is being used by multiple companies? If any one by mistakenly made the delegate a null, then every company whoever is using that delegate will get affected. So how do we resolve this issue?

Now, I proudly introduce you all the hero to solve this problem who is none other than "Events". Events cannot be set to null using assignment operator. It may become null only if none of the listeners are attached to the event. Also, only the listener class can subscribe or remove its listening method from the event list. No one else can remove on behalf of.

So, what are events and how to create events?
Events are special keywords which are going to be used with the variable of type delegate.

We will take the delegate variable created in our "DataProcessor" class and convert it into event. Below is the line of code to declare variable of type delegate.

public DataProcessUpdateHandler updateHandledBy = null;

Now add event keyword with this line to make it as event.

public event DataProcessUpdateHandler updateHandledBy = null;

Now it become event. Once you do this change in the existing code, automatically I got the compilation error on the line which was setting up the "null" value.
event null error

Now, subscriber2 cannot make the delegate as null. If they do not want to listen to the updated status, then they need to unsubscribe from that delegate using "-=" operator like below. That will only remove "DataProcessUpdateHandler" method of subscriber2 instance

_dataProcessor.updateHandledBy -= DataProcessUpdateHandler;

That's all about events and delegates. I hope I cleared your confusion little bit.

Your answer

Preview

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2015 pinfaq.com
...