Breaking News

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);
 
In the above declaration, the first parameter (sender) in the above declaration specifies the object that fired the event. and the second parameter (e) holds the data that can be used in the event handler. MyEventArgs is derived from the class EventArgs. EventArgs is the base class of more specialized classes, like MouseEventArgs etc.
 
For a GUI event, you can use objects of these specialized EventArgs classes without creating your own specialized EventArgs classes. However, for non-GUI events, you need to create your own specialized EventArgs class to hold the 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 the case of an 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 the .Net framework. The second step 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:
 
Example
 
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 
{ 
 	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); 
 	} 
}
 
Practical Example(Delegates):
 
testDelegate.cs
 
using System;
using System.Collections.Generic;
using System.Text;

namespace testDelegate
{
class Program
{
public delegate int simpleDelegate(int a, int b);
public int addNumber(int a, int b)
{
return (a + b);
}

public int mulNumber(int a, int b)
{
return (a * b);
}
static void Main(string[] args)
{
Program clsDlg = new Program();
simpleDelegate addDelegate = new simpleDelegate(clsDlg.addNumber);
simpleDelegate mulDelegate = new simpleDelegate(clsDlg.mulNumber);
Console.WriteLine("Enter first number--");
      string firstnum = Console.ReadLine();
      Console.WriteLine("Enter second number--");
        string secondnum = Console.ReadLine();
  int addAns = addDelegate(int.Parse(firstnum), int.Parse(secondnum));
 int mulAns = mulDelegate(int.Parse(firstnum), int.Parse(secondnum));
 Console.WriteLine("Result by
 calling the addNum method using a delegate: {0}", addAns);
 Console.WriteLine("Result by 
calling the mulNum method using a delegate: {0}", mulAns);
            Console.Read();
 }
 }
}
 
The Output is:
 
img
 
Practical Example (Events):
 
testEvents.cs
 
using System;
using System.Collections.Generic;
using System.Text;

namespace testEvents
{
    //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 
    { 
 	    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);
            Console.ReadLine();
 	    } 
    }
}

 
The Output is:
 
img
 
To Download Delegates and Events example Click here.
 
To view downloaded examples, Please Ensure that .NET Framework is installed on your system.