Events and Delegates - Part II

by agrace 8. September 2007 09:24

Hungry Geek You can read part one of this topic here. This part presents a simple example of how to publish and subscribe to an event that does not send data. Note that events such as button clicks, that generate no data can avail of the EventHandler delegate provided in the class library.

Publish an Event - Five Steps:

* Define type inherited from EventArgs to contain any event-related data. If there is no data, use pre-defined EventArgs type

* Define delegate that specifies prototype of event handler. If the events generates no data, use pre-defined EventHandler delegate

* Define an event based on the delegate type

* Define a protected, virtual method to raise the event

* When the event occurs, call the protected, virtual method above

class ButtonPublisher
     public delegate void EventHandler(object sender, EventArgs e);
     public event EventHandler Click;

     // Each class that publishes an event provides a
     // protected, virtual method to raise that event.
     // The "On" name prefix makes this easy to spot.
     protected void OnClick()
         // Check for subscibers
         if (Click != null)
             // Notify them
             Click(this, null);

     // Raise the event
     public void PerformClick()


Subscribe to an Event - Three Steps:

* Implement an event handler with same signature specified by the event's delegate object

* Create a delegate object specified for the event. This delegate refers to the event handler method (see below)

this.Click += new EventHandler(ButtonClick_Handler);


* Subscribe to event by attaching event handler to the event (see above). Use the += operator so as not to cancel any previously registered delegates

class Subscriber
     static void Main(string[] args)
         ButtonPublisher button = new ButtonPublisher();
         // Create new delegate object and subscribe to event
         button.Click += new ButtonPublisher.EventHandler(ButtonClick_Handler);

     static public void ButtonClick_Handler(object sender, EventArgs e)
         Console.WriteLine("Button Clicked");

         // Keep console window open long enough to read!


Happy coding!

Tags: ,


Pingbacks and trackbacks (1)+