Library tutorials & articles

Event Handling in .NET Using C#

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);    
   }
}

Comments

  1. 25 Apr 2007 at 04:18

    While it's very nice to know the "How" when explaining syntax, more importantly is they "why" in terms of practical real-life use within a C# application.  It would be nice of you would have included some true examples of when you would need to use one and why.

  2. 24 Nov 2005 at 15:04

    This is one of the best articles i have come across on Delegates and Event.. Good Job!

  3. 02 Jun 2004 at 12:03

    Line:


    public class MyEventArgs  EventArgs {


    should read:


    public class MyEventArgs : EventArgs {


    Otherwise, great article!

  4. 22 Apr 2004 at 17:24

    Can anyone help me pls!!!


    I am facing a big problem to code the gui buttons!! I am doing a C# project. this project consists of a telephone graphical user interface!!


    can anyone tell me what can i do to code the number buttons to display the telephone number into a textfield...


    I need this urgent plsssss!!!!!!


    Thanks for your help!!!!!!

  5. 28 Jul 2003 at 16:32

    I need to know how can I trap an Outlook Event (Saving an Item) using C#. Any example will be highly appreciated.


    Thanks in advance!!

  6. 12 Jul 2003 at 03:52

    How can I create asynchrous events?
    Using delegates and events I get synchronous calls?
    Please advise.

  7. 28 Apr 2003 at 17:34
    Hi,

    I am using certain, COM Components, I need to know the delegate signature, to create event handler. Is there any tools to do this? or if I need to do manually which is the easiast way to know the exact signature of those events raised by the COM components.
  8. 20 Mar 2003 at 06:56

    Very good example. it can be better hadling browser events, with .NET of course.

  9. 01 Jan 1999 at 00:00

    This thread is for discussions of Event Handling in .NET Using C#.

Leave a comment

Sign in or Join us (it's free).

Deepak Dutta

Related discussion

Related podcasts

  • Object-Oriented Programming in Ruby

    In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...

Events coming up

  • Dec 7

    An Event Apart San Francisco 2009

    San Francisco, United States

    From the makers of A List Apart: An Event Apart is an intensely educational two-day conference for passionate practitioners of standards-based web design. If you care about code as well as content, usability as well as design, An Event Apart is th...

Want to stay in touch with what's going on? Follow us on twitter!