Event Handling in .NET using C#


Summary

In this article I discuss the event handling model in .NET using C#. The discussion starts with an introduction to the concept of delegates and then it extends that concept to events and event handling in .NET. Finally, I apply these concepts to GUI event handling using windows forms. Complete code is provided in each step of the discussions.

Introduction

Event handling is familiar to any developer who has programmed graphical user interfaces (GUI). When a user interacts with a GUI control (e.g., clicking a button on a form), one or more methods are executed in response to the above event. Events can also be generated without user interactions. Event handlers are methods in an object that are executed in response to some events occurring in the application. To understand the event handling model of .Net framework, we need to understand the concept of delegate.

Delegates in C#

A delegate in C# allows you to pass methods of one class to objects of other classes that can call those methods. You can pass method m in Class A, wrapped in a delegate, to class B and Class B will be able to call method m in class A. You can pass both static and instance methods. This concept is familiar to C++ developers who have used function pointers to pass functions as parameters to other methods in the same class or in another class. The concept of delegate was introduced in Visulal J++ and then carried over to C#. C# delegates are implemented in .Net framework as a class derived from System.Delegate. Use of delegate involves four steps.

1. Declare a delegate object with a signature that exactly matches the method signature that you are trying to encapsulate.
2. Define all the methods whose signatures match the signature of the delegate object that you have defined in step 1.
3. Create delegate object and plug in the methods that you want to encapsulate.
4. Call the encapsulated methods through the delegate object.

The following C# code shows the above four steps implemented using one delegate and four classes. Your implementation will vary depending on the design of your classes.

using System;
//Step 1. Declare a delegate with the signature of the encapsulated method
public delegate void MyDelegate(string input);
//Step 2. Define methods that match with the signature of delegate declaration
class MyClass1
{
public void delegateMethod1(string input)
{
Console.WriteLine("This is delegateMethod1 and the input to the method is {0}",input);
}
public void delegateMethod2(string input)
{
Console.WriteLine("This is delegateMethod2 and the input to the method is {0}",input);
}
}
//Step 3. Create delegate object and plug in the methods
class MyClass2
{
public MyDelegate createDelegate()
{
MyClass1 c2=
new MyClass1();
MyDelegate d1 = new MyDelegate(c2.delegateMethod1);
MyDelegate d2 =
new MyDelegate(c2.delegateMethod2);
MyDelegate d3 = d1 + d2;
return d3;
}
}
//Step 4. Call the encapsulated methods through the delegate
class MyClass3
{
public void callDelegate(MyDelegate d,string input)
{
d(input);
}
}
class Driver
{
static void Main(string[] args)
{
MyClass2 c2 =
new MyClass2();
MyDelegate d = c2.createDelegate();
MyClass3 c3 =
new MyClass3();
c3.callDelegate(d,"Calling the delegate");
}
}

Event handlers in C#

An event handler in C# is a delegate with a special signature, given below.

public delegate void MyEventHandler(object sender, MyEventArgs e);

The first parameter (sender) in the above declaration specifies the object that fired the event. The second parameter (e) of the above declaration holds data that can be used in the event handler. The class MyEventArgs is derived from the class EventArgs. EventArgs is the base class of more specialized classes, like MouseEventArgs, ListChangedEventArgs, etc. For GUI event, you can use objects of these specialized EventArgs classes without creating your own specialized EventArgs classes. However, for non GUI event, you need to create your own specialized EventArgs class to hold your data that you want to pass to the delegate object. You create your specialized EventArgs class by deriving from EventArgs class.

public class MyEventArgs : EventArgs
{
public string m_myEventArgumentdata;
}

In case of event handler, the delegate object is referenced using the key word event as follows:

public event MyEventHandler MyEvent;

Now, we will set up two classes to see how this event handling mechanism works in .Net framework. The step 2 in the discussion of delegates requires that we define methods with the exact same signature as that of the delegate declaration. In our example, class A will provide event handlers (methods with the same signature as that of the delegate declaration). It will create the delegate objects (step 3 in the discussion of delegates) and hook up the event handler. Class A will then pass the delegate objects to class B. When an event occurs in Class B, it will execute the event handler method in Class A.

using System;
//Step 1 Create delegate object
public delegate void MyHandler1(object sender,MyEventArgs e);
public delegate void MyHandler2(object sender,MyEventArgs e);
//Step 2 Create event handler methods
class A
{
public const string m_id="Class A";
public void OnHandler1(object sender,MyEventArgs e)
{
Console.WriteLine("I am in OnHandler1 and MyEventArgs is {0}", e.m_id);
}
public void OnHandler2(object sender,MyEventArgs e)
{
Console.WriteLine("I am in OnHandler2 and MyEventArgs is {0}", e.m_id);
}
//Step 3 create delegates, plug in the handler and register with the object that will fire the events
public A(B b)
{
MyHandler1 d1=
new MyHandler1(OnHandler1);
MyHandler2 d2=
new MyHandler2(OnHandler2);
b.Event1 +=d1;
b.Event2 +=d2;
}
}
//Step 4 Calls the encapsulated methods through the delegates (fires events)
class B
{
public event MyHandler1 Event1;
public event MyHandler2 Event2;
public void FireEvent1(MyEventArgs e)
{
if(Event1 != null)
{
Event1(
this,e);
}
}
public void FireEvent2(MyEventArgs e)
{
if(Event2 != null)
{
Event2(
this,e);
}
}
}
public class MyEventArgs : EventArgs
{
public string m_id;
}
public class Driver
{
public static void Main()
{
B b=
new B();
A a=
new A(b);
MyEventArgs e1=new MyEventArgs();
MyEventArgs e2=
new MyEventArgs();
e1.m_id ="Event args for event 1";
e2.m_id ="Event args for event 2";
b.FireEvent1(e1);
b.FireEvent2(e2);
}
}

GUI Event Handling in C#

Event handling in Windows Forms (.NET frame work that supports GUI application) employ the .NET event handling model described earlier. We will now apply that model to write a simple application. The application has one class, MyForm, derived from System.Windows.Forms.Form class. Class MyForm is derived from Form class. If you study the code and the three comment lines, you will observe that you do not have to declare the delegates and reference those delegates using event keyword because the events (mouse click, etc.) for the GUI controls (Form, Button, etc.) are already available to you and the delegate is System.EventHandler. However, you still need to define the method, create the delegate object (System.EventHandler) and plug in the method, that you want to fire in response to the event (e.g. a mouse click), into the delegate object.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
public class MyForm : Form
{
private Button m_nameButton;
private Button m_clearButton;
private Label m_nameLabel;
private Container m_components = null;
public MyForm()
{
initializeComponents();
}
private void initializeComponents()
{
m_nameLabel=
new Label();
m_nameButton =
new Button();
m_clearButton =
new Button();
SuspendLayout();
m_nameLabel.Location=
new Point(16,16);
m_nameLabel.Text="Click NAME button, please";
m_nameLabel.Size=
new Size(300,23);
m_nameButton.Location=
new Point(16,120);
m_nameButton.Size=
new Size(176, 23);
m_nameButton.Text="NAME";
//Create the delegate, plug in the method, and attach the delegate to the Click event of the button
m_nameButton.Click += new System.EventHandler(NameButtonClicked);
m_clearButton.Location=
new Point(16,152);
m_clearButton.Size=
new Size(176,23);
m_clearButton.Text="CLEAR";
//Create the delegate, plug in the method, and attach the delegate to the Click event of the button
m_clearButton.Click += new System.EventHandler(ClearButtonClicked);
this.ClientSize = new Size(292, 271);
this.Controls.AddRange(new Control[]
m_nameLabel,m_nameButton,m_clearButton});
this.ResumeLayout(false);
}
//Define the methods whose signature exactly matches with the declaration of the delegate
private void NameButtonClicked(object sender, EventArgs e)
{
m_nameLabel.Text="My name is john, please click CLEAR button to clear it";
}
private void ClearButtonClicked(object sender,EventArgs e)
{
m_nameLabel.Text="Click NAME button, please";
}
public static void Main()
{
Application.Run(
new MyForm());
}
}

Conclusion

Other popular object oriented languages like, Java and Smalltalk do not have the concept of delegates. It is new to C# and it derives its root from C++ and J++. I hope that the above discussions will clear this concept to programmers who are starting out C# as their first object oriented language. If you are using Visual Studio IDE for your C# GUI development, attaching your delegate methods to the events generated by GUI controls (like mouse click on a button) can be done without you writing the code. Still, it is better to know what is going on under the hood.

Up Next
    Ebook Download
    View all
    Learn
    View all