C# Events


An event is defined in C# as 'a member thatenables an object or class to provide notifications'. Now, let us seein detail what an event is and how notifications are provided in C#.In an application, the change in status (or certain properties) of anobject may result in some actions to be performed. For e.g., consider adialog box with some buttons in it. Pressing any of these buttons willhave to perform an action, for e.g., starting a new process or closingthe dialog. This action will be defined by the user who is developingthe application. Other than this, when the button is pressed, certainactions should be performed at the system level. These include changingthe appearance of the button to give the user a feeling that the buttonis being pressed and so on. In common programming languages, this isdone by placing the code that should be executed when button clickoccurs in some functions and invoking these functions when the userclicks the button. Here, clicking the button is normally referred to asan 'Event' and all the associated functions that are called as a resultof an event as 'Event Handlers'. When an event occurs, all the eventhandlers are 'notified' (this simply means that all the event handlerfunctions are invoked). To invoke all these functions when an event istriggered, the event should know what all functions are associated withit. We can now look at how events are implemented in C# and how it isassociated with event handlers.

Let us start with an example. Consider that weare designing a Button control that can be used by other developerswhile developing screens. The Button can be placed in a dialog (orscreen) and will have some properties associated with it. When a userclicks the button, some actions are to be performed that will bedefined only at the time of coding the screen. Assume that this pieceof code (i.e., the operations that should be performed when any of thebuttons are clicked) will be put in a function named 'onButtonClick' bythe user. The function will look like

public void onButtonClick (object source, int clickCount) {
//Define the actions that should be performed.
}

Here, we have two parameters for the function.The first parameter is an object that identifies the source of event. Ascreen (or dialog) may contain more than one button and this parameteris used to identify which button is clicked by the user (the actions tobe performed by each button will be different). The second parameter isan integer that indicates whether the action is a single click ordouble click (that may be of little use in the current context).The first step for implementing the event in button class is to declarea delegate for representing the event handler function (onButtonClick).The delegate declaration will be as follows:

public delegate void ButtonEventHandler(object source, int clickCount)

where ButtonEventHandler is the delegatename.(For those who do not have an idea about delegates- Delegates canbe considered as 'function pointers' which is used to represent orinvoke functions. The delegate type should be same as the correspondingfunction it represents, i.e., the parameters and return type ofdelegates and the corresponding function should be identical.). Thedelegate type ButtonEventHandler represents the function type that canbe associated with the click event, i.e., any function that accepts twoparameters (object and int) and returning void, can be associated withthe click event. Now we can proceed with the event declaration. Let theevent name be 'ButtonClick'. The event declaration will be as follows:

public event ButtonEventHandler ButtonClick;

The event declaration should have the keyword'event' followed by the delegate type. The next step is associating theevent handler function (onButtonAction) with the event (ButtonClick).This is to be done because the ButtonClick event should know about thefunctions that are to be executed when the event is triggered. Theoperator += is used to achieve this as shown in the following code:

b.ButtonClick += new ButtonEventHandler(onButtonAction);

Here, b is an instance of the class Button.(Also, note that the onButtonAction should have the same parameter andreturn types as ButtonEventHandler delegate.)

Now consider that the event is triggered. Thiscan be done by the user or another process. In our case, the event istriggered when a user clicks on any of the buttons. On doing this, allthe associated functions (onButtonAction in the current context) ofButtonClick event should be executed. This can be performed using thefollowing code:

ButtonClick(this, count)

The parameters of ButtonClick should matchwith the delegate type (ButtonEventHandler). The following codeconsolidates all our discussion till now:

//declaring the event handler delegate
delegate void ButtonEventHandler(object source, int clickCount);

class Button
{
//declaring the event
public event ButtonEventHandler ButtonClick;

//Function to trigger the event
//This will be called when the user clicks the button
public void clicked(int count)
{
//Invoking all the event handlers
if (ButtonClick != null) ButtonClick (this,count);
}
}

public class Dialog
{
public Dialog()
{
Button b = new Button();

b.ButtonClick += new ButtonEventHandler(onButtonAction);
b.clicked(1);
}
}

//Event Handler function
public void onButtonAction(object source,int clickCount)
{
//Define the actions to be performed on
//button click here.
}

Before going to a sample program, we willdiscuss some more details regarding the event operations. The operator'-=' will remove the corresponding function from the Event, opposite tothe behaviour of '+='. The following code

ButtonClick = null

will remove all the event handler functionsfrom ButtonClick. Also, if you want to check whether any event handlers(or functions) are attached to the event, the code

if (ButtonClick != null)
can be used.

Finally, a sample program is given which adds and removes more than one event handler:

using System;

//declaring the event handler delegate
delegate void ButtonEventHandler(object source,int clickCount);

class Button
{
//declaring the event
public event ButtonEventHandler ButtonClick;

//Function to trigger the event
public void clicked(int count)
{
Console.WriteLine("\nInside Clicked !!!");
//Invoking all the event handlers
if (ButtonClick != null) ButtonClick(this,count);
}
}
public class Dialog
{
public Dialog()
{
Button b = new Button();

//Adding an event handler
b. ButtonClick += new ButtonEventHandler(onButtonAction);
//Triggering the event
b.clicked(1);

b.ButtonClick += new ButtonEventHandler(onButtonAction);
b.clicked(1);

//Removing an event handler
b.ButtonClick -= new ButtonEventHandler(onButtonAction);
b.clicked(1);

b.ButtonClick -= new ButtonEventHandler(onButtonAction);
b.clic
ked(1);
}
static void Main()
{
new Dialog();
}

//Event Handler function
public void onButtonAction(object source,int clickCount)
{
Console.WriteLine("Inside Event Handler !!!");
}
}

The output of the program will be as follows:

Inside Clicked !!!
Inside Event Handler !!!

Inside Clicked !!!
Inside Event Handler !!!
Inside Event Handler !!!

Inside Clicked !!!
Inside Event Handler !!!

Inside Clicked !!!

Related Articles :

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!