delegate and event
delegate and event are closely connected in C#. With delegate alone, the type declared by delegate works just as the function pointer in C/C++. Thus we may see codes like this:
//declare delegate type
public delegate void myDelegate(param_list);
//define functions with the same param_list as in myDelegate
class A
{
public void func1(param_list){//definition code}
public void func2(param_list){//definition code}
};
//make use of delegate type just declared
myDelegate md1 = new myDelegate(a.func1);
myDelegate md2 = new myDelegate(a.func2);
md1(param_list);
md2(param_list);
However, while related with event, delegate will do a lot more work than just the function type kind. An event is inside an object, with type of the delegate we just defined. The application invokes/triggers the event of the object by calling the object's method, the object then delegates the handling of the event to the handler the delegate type points to. To be concisely, App invokes obj's event, event use a delegated handler to handle the event. The following mentions these procedures by using a simple demo.
//1.declare our delegate type
public delegate void myEventHandler(object sender, System.EventArgs e);
//2.derive class from System.EventArgs to store information of event.
//Not used here thus omitted.
//3.declare event in the class which may invoke event
public class myEventClass
{
//declare event with delegate type
public event myEventHandler aEvent;
//other members and methods...
};
//4.implement handler with the same signature of the delegate type we just declared.
public void myEventFunc(object sender, System.EventArgs e)
{
Console.WriteLine("Handler function called!");
}
//5.define evoking function
//in myEventClass
public void OnMyEvent(System.EventArgs e)
{
if (aEvent != null)
aEvent(this, e);
}
//6.register handler to the event of the object and trigger by calling the obj's invoking function.
static void Main(string[] args)
{
//create a event class (which is the source of the event)
myEventClass objEvent = new myEventClass();
//register the handler into the event
objEvent.aEvent += new myEventHandler(objEvent.myEventFunc);
EventArgs e = new EventArgs(); //not derived args here
objEvent.OnMyEvent(e);
}