Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Events and Delegates in .NET Framework

In this article we will see how to work with events and Delegates in .NET Framework

Events

In the beginning, the programming process was purely linear, it means, the code was executed in a sequencial way, line after line. On console applications, we can still see this kind of code, once we have only one screen in which is shown characters, and the only way of interaction of the user is using the keyboard to insert data when asked.

Example of linear program

Figure 1: Example of linear program

The Figure 1 shows one example of linear application. The information of the client are inserted always in the demonstrated sequence, the user can't choose to enter his E-mail first, for instance.

With the advent of more sophisticated interfaces, containing buttons, text boxes, among other diverse graphic elements, the code of the applications has become divided in blocks that are executed according with the interaction with the user (clicking on a button, for instance).

Example of non-linear application

Figure 2: Example of non-linear application.

On the other hand, The Figure 2 exhibits one window interface that has the same finality of the illustrated screen on the previous figure. However, on this example, the user can choose between insert the information in the order that pleases him, as can click on options "Save" and "Cancel" at any moment, not only after finishing the information insertion.

In this case, the data processing and the recording or not of these information, will be done when the user clicks on one of the buttons. The programmer can not predict when and if it will occur, but a code block must be executed when the button is clicked on.

In fact, when the user clicks on a button, one event called Click is fired, and is at that event that the programmer will work to execute its specific routines.

An event is "something" that occurs in consequence of an action, in the given example, the action is the button pressing.

Observation: the reader can find a little bit repetitive the using of the term "event", the fact is this is the simplest way to approach the matter.

Making a reference to the physical world, we can come up with the following example: as we turn the ignition key of a vehicle, the same is turned on. The action, on this case, of turning the ignition key made the event of the vehicle turned on possible. However, on turning the vehicle on, other stuff need to be done, as such light up the panel lights. So, bringing it back to programming, we can consider Vehicle as a class and Started (Vehicle turned on) as been the event that occurs as the key is turned on. The code of this event could be, for instance, similar to the one of the Listing 1.

Listing 1: Code representation of an event

CLASS Vehicle
	EVENT Started
		Turn_On_Panel_Lights();
		//Other procedures
	END_EVENT
END_CLASS

On .NET Framework are many the events that can be fired during an application. Events that occur, for example, on the pressing of a button, as already have been said, on the changing of a text field, on opening and closing of a form, and on many other situations.

The objects that fire them (called event senders), however, don't know what must be done when certain event occurs. For this is necessary to inform which method (called event handler) will be executed at each occurrence of this event. This is not an difficult task and we do it every day, even automatically.

Create one "Windows Forms Application" and then add a button (which must be named button1, by default) to the screen, Then give it a double click and we'll be redirected to the code area, where the programming itself is made. There'll be created a void method in the form's code, as exhibited on Listing 2.

Listing 2: Methods created on double-clicking a button

//In C#
private void button1_Click(object sender, EventArgs e)
{
}

'In VB.NET
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
End Sub

On VB.NET, we see in the method's signature a phrase "HandlesButton1.Click", it means, this method is treating the event Click of the button. So, when the user clicks on the button, the code that's on the body of the method Button1_Click will be executed. That simple.

On C#, however, nothing makes reference to the button (excluding the method's name, which doesn't mean a lot). Then, how we know that this method will be executed in the event Click of the button1? In C# case, the answer is a little less explicit. We need to open the file Form1.Designer.cs (this file can be found the the Solution Explorer guide, expanding the Form1, as shown in the Figure 3).

Designer's file of the form in the Solution Explorer

Figure 3: Designer's file of the form in the Solution Explorer

In this file, we'll see a similar stretch as the one exhibited in the Figure 4.

Click's event connection to the method button1_Click

Figure 4: Click's event connection to the method button1_Click

The highlighted line shows us that we "sum" to the event Click an object of the type EventHandler, which receives as a parameter the previously created method. This is the used syntax in C# to associate one method to an event. Let us define then some methods and link them to the events manually. This will ease the understanding of the functioning process.

In the form's code, add the following methods:

Listing 3: Methods to treat the Click event of the button

//In C#
private void metodo_click1(object sender, EventArgs e)
{
    MessageBox.Show("Method 1");
}

private void metodo_click2(object sender, EventArgs e)
{
    MessageBox.Show("Method 2");
}

//In VB.NET
Private Sub metodo_click1(sender As System.Object, e As System.EventArgs)
   MessageBox.Show("Method 1")
End Sub

Private Sub metodo_click2(sender As System.Object, e As System.EventArgs)
   MessageBox.Show("Method 2")
End Sub

Notice that in the version VB.NET there's not the "Handles Button1.Click", because these methods are not specifically to treat the event Click of the button, but, we'll use them to this goal.

Now, on the event Load of the form (double-clicking the main form) let's associate one of the methods to the event of the button, as shows the Listing 4.

Listing 4: Associating one method to an event manually

//In C#
private void Form1_Load(object sender, EventArgs e)
{
    button1.Click += new EventHandler(metodo_click1);
}

//In VB.NET
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    AddHandler Me.Button1.Click, AddressOf Me.metodo_click1
End Sub

Executing the project and clicking on the button, we'll have a dialog box with the text "Method 1". It is suggested then that the reader switch the parameter "method_click1" to "method_click2" and then execute the project again. This time the message will be "Method 2" because the associated method to the event is the mehod_click2.

At this point, may appear a very common doubt: it is possible to associate more than one method to the same event? The answer is YES. As we saw, the methods are "sum" to the event by the operators "+=" and "Addhandler". So, do yourself the test and add the two methods to the event (one line to each method) and then execute the project. The two messages will be exhibited.

The listing 4 allow us observe and understand the syntax, on both languages, in order to "add" a method to an event. In practical terms, what it is done is inform to the object one reference to the method that'll treat its event. On C++, for instance, there're the called pointers to functions, that have the same objective. On .NET Framework, however, these pointers have another name: delegate.

Delegates

At this point of the article, we've already passed by the delegates, without knowing them as such. Remember the EventHandler? It's a delegate, that's nothing more than an object that references one method according to its signature (return and parameters). Notice that every method we've defined to treat the event Click of the button had void return and receive two parameters. We did it this way so the delegate EventHandler was defined to reference methods with that structure.

The Listing 5 shows the Event Handler declaration in the namespace System.

Listing 5: EventHandler delegate declaration

//In C#
public delegate void EventHandler(Object sender, EventArgs e);

//In VB.NET
Public Delegate Sub EventHandler (sender As Object, e As EventArgs)

This way, the methods responsible for treating the events that use the EventHandler must possess that signature in order to the operation to be valid. Other events use other delegates, such as the DragEventHandler and the KeyEventHandler.

Anonymous Methods

Lastly, we shall see briefly how to work with the called anonymous methods that were added in the C# 2.0 version (they are not available natively for VB.NET) and allow us to create delegates that do not reference directly one method previously defined, but a block of code (with the method's same function). Let us see it in practical terms, with the same example of the button saw previously, how this way of event treatment works.

On the Load event of the form, where we referenced the method method_click1 and method_click2, let's replace the code for the content of the Listing 6.

Listing 6: Anonymous method to treat the button's Click event

private void Form1_Load(object sender, EventArgs e)
{
    button1.Click += delegate(Object sd, EventArgs ea)
                    {
                        MessageBox.Show("Anonymous Method");
                    };
}

Notice that even being an anonymous method (there's no previous declaration) the parameters must coincide with the declaration of the delegate responsible for the event treatment, in this case, the EventHandler. Only the parameter's names have been altered, because there's already "sender" and the "and" of the method Form1_Load inside of which the delegate was created.

Conclusion

The possibility to define methods to treat events manually and dynamically are very useful, for instance, when we create objects on running time and we need the routines to be executed by the user's interaction with these objects

This way, I conclude this article in which have been presented the Events, Delegates, and the Anonymous Methods, on the .NET platform. I hope this article may be of use.

Thanks to the reader's attention, see you next time.



Microsoft MVP, Bachelor in Science And Technology, Editor and Consultant at DevMedia with more than 7 years of experience in software development.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login