events and delegates in C#


In my previous article we discussed about the concept of the delegates. We created a simple delegate which can encapsulate methods that takes 2 input parameters of int type and return an int type value.

Moving on with this concept, now we will be discussing the relation between an event and a delegate.

What is an event ?

Just a simple explanation, an event is notification that something has happened. For ex, a button click event notifies that user has pressed a button. In simple language, an event signifies that something has happened from the user end.

Normally for controls that we add in our .aspx pages, we bind the events from the html mark-up side, in .cs file. But when we create the dynamic controls, we have to bind the events for the controls using the code. For ex, to bind event for a dynamic button, we bind the event as :

btn.Click += new EventHandler(btn_Click); // Point of interest

and define the method as :

void btn_Click(object sender, EventArgs e)
{
 // Code goes here
}

Here, EventHandler is a built-in delegate which is encapsulating method in itself and the method btn_Click(object sender, EventArgs e), a method definition is referred to as the Event handler for the event button click.

So we can see here that the delegate definition that we have, fits here perfectly. But what exactly does the line btn.Click += new EventHandler(btn_Click) results in ?

So let’s try to find this out. To start with we will need to discuss some basic stuff that goes behind the scenes in the declaration above : 

1. Events when attached using the above syntax, create a publisher subscriber pattern. For ex. there are two entities A and B. Whenever, A performs any action, then B receives a notification that some action has been performed by A.

2. Delegates act as an intermediate between the publisher and the subscriber.

3. A delegate used to manage/create an event is generally referred to as event handler (and we will also refer to this as same).

4. Any method of the subscriber, which is executed, when publisher executes something, can be referred to as Event handling method.

5. An event can be declared in 2 ways, Field-like and Property-like. We will be using the Field -like syntax.

6. When we declare an event, we also specify its type, like we specify the type of any variable or property that it is an integer or string. But the type of event is of delegate only, which could be any built-in delegate or any custom delegate.

Now we will discuss the above points using a sample. Our scenario is, we have a page and a usercontrol added on it. We have a button on the usercontrol. On click of the button on the usercontrol, we will be receiving a notification on the main page, that usercontrol button has been pressed.

The page-usercontrol combination form the publisher-subscriber pattern that we discussed in point 1, as the main page receives a notification whenever the button on usercontrol is clicked. So here usercontrol will act as publisher and the page will act as a subscriber.

Next, we will declare an event handler, using a custom delegate in our user control, using the following syntax :

DelegateEvent Syntax

The above declaration of the event handler delegate and the event, forms the points 3, 5 and 6. So our event is now ready to be published from the publisher. To publish this, we need to do the following code on the click of the button :

EventPublishing

Here, on click of the button event, we first check if any subscriber has subscribed for the notification. If yes, then we send the notification, using the event.

Now, how the subscriber will subscribe to this notification? To do this, we need to do the following code :

Subscriber

To access the event of the usercontrol, we access it like we would have done to access any of its property. Then we attach the delegate with the event using the “+=” operators. The method which our delegate refers to in the above code is the event handling method, which is nothing but the point 4 that i mentioned above.

This above subscription to the event has one important point that can help us understand that why we are passing the delegates to the event. This the Point of interest that i mentioned in the very starting of the article.

The point is that an event internally consists of 2 methods, which are add & remove. These methods take a delegate as an input parameter. So the notation “+=” and “-=” result in adding & removing the delegate to events list for invocation. The type of delegate which these event methods take as an input parameter, is similar to the one which is the return type of the event which we declared earlier in our code. So, when we attach the delegate with the event here, it encapsulates the method in it and this method is executed when the subscriber receives any notification. 

Now another question arises here, could we have done something like this :

ucSampleControl.MyEvent = new ucDelegateSample.SampleDelegate(ucSampleControl_MyEvent);

i.e replace “+=” with “=”. Try it and you will receive the following error :

The event ‘ucDelegateSample.MyEvent’ can only appear on the left hand side of += or -= 

To explain this consider the statements

int a = 10;  and then change it to a = 15. What will be the value of a finally then ?

It would have become 15 then. Similar is the case here. Had we allowed the use of only “=” to attach the event, it would have replace all the attached subscribers from the event handler and attached itself to it. So you can use “=”, only if the event where it is declared and attached are in the same class. Otherwise, it restricts other subscribers to bind using the “=” and allow them only to add themselves into the invocation list. This something similar to append in stringbuilder function.

So here we can see that the delegate acts as an intermediate between the usercontrol and the page, and helps the page to receive the notification from the usercontrol, which is the point 2 that i mentioned earlier.

So this was all about the relation between events and delegates. Happy Coding…!!!

Advertisements

About Jasminder

.Net developer and blogger by profession, keen to learn new technologies, love nature, music and cricket.
This entry was posted in C# and tagged . Bookmark the permalink.

I have a suggestion..

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s