“Chishiki” is Japanese for “knowledge.” e-chishiki.com aims to bring software developers, information security professionals, IT executives and other IT pros a rich body of knowledge in the form of articles, interviews, tutorials and technical discussions. Our contributors are among the biggest names in the Indian IT industry and include noted authors, educators and practitioners.
C# Programming Series
C# Events and Delegates II
Yashavant Kanetkar
Events
To understand events, consider the following program:
using System;
namespace Sample
{
public class mouseeventargs
{
public int x, y;
public mouseeventargs(int x1, int y1)
{
x = x1;
y = y1;
}
}
public delegate void click(object m, mouseeventargs e);
public class MyForm
{
public event click c1;
public void mouseclick()
{
mouseeventargs m = new mouseeventargs(10, 20);
c1(this, m);
}
}
class MyForm1 : MyForm
{
public MyForm1()
{
c1 += new click(button_click);
mouseclick();
}
static void Main(string[] args)
{
MyForm1 f = new MyForm1();
}
public void button_click(object m, mouseeventargs e)
{
Console.WriteLine("Mouse Coordinates: " + e.x + " " + e.y);
Console.WriteLine("Type is: " + m.GetType().ToString());
}
}
}
The output of the program would be
Mouse Coordinates: 10 20
Type is: Sample.MyForm1
In this program we have declared 3 classes-mouseeventargs, MyForm and MyForm1 derived from MyForm. The mouseevntargs class corresponds to the EventArgs class. This class contains two int variables x and y and a constructor to initialize them. We have declared a multicast delegate click whose signature is same as the event handler button_click( ). The MyForm class here is an event raiser class and hence contains an event as a data member called c1 of the type click. It also contains a method called mouseclick( ). In this method we have created an object of the mouseeventargs class. In the statement,
c1(this, m);
c1 represents (is a delegate for) button_click( ). this contains the reference of MyForm object (event raiser) and m is a reference of the mouseeventargs object. In the MyForm1 class, we have defined the method button_click( ) (i.e. event handler). When the compiler encounters the statement
c1 += new click(button_click);
it creates an event object (delegate object) that wraps up button_click( ) method. So whenever the c1 event is raised (or called, as in this program), the method button _click( ) will get executed.



