Home > Articles > Programming > C#

  • Print
  • + Share This
From the author of

From the author of

Events and Delegates

C# has class members called events that accept one or more delegates. The following code shows how to hook up events and delegates:

   this.btnOK.Click += new System.EventHandler(this.btnOK_Click);

The Click event accepts an EventHandler delegate, which specifies the btnOK_Click() method that gets called when the event fires. Here's the EventHandler delegate declaration:

   Public delegate void EventHandler(Object sender, EventArgs e);

A delegate is a C# object that provides type-safe late-bound access to methods. A method conforming to the EventHandler signature must have Object and EventArgs parameters and must return void. Here's how the event is declared in the Button class, which btnOK is a type of:

   public event EventHandler Click;

Events are declared to accept a certain type of delegate. All delegates assigned will be invoked when the event fires. Here's the shell of the btnOK_Click() method.

   private void btnOK_Click(object sender, System.EventArgs e)
   {
     // some implementation
   }

In contrast, Java doesn't have an event class member, nor does it have delegates. It commonly implements event behavior via inner classes and methods. Here's how to hook up the method to be called with a class that implements event behavior:

    btnOK.addActionListener(new java.awt.event.ActionListener() {

        public void actionPerformed(ActionEvent e) {
            btnOK_actionPerformed(e);
        }
    });

This is a far cry from the simplicity of C#'s += operator. For completeness of comparison, here's the method:

    void btnOK_actionPerformed(ActionEvent e) {
     // some implementation
    }

C# implements delegates and events as first-class language elements. In contrast, the Java delegation event model is essentially a bolted-on technology, providing a complex and bloated solution to an original event model that never worked well in the first place.

  • + Share This
  • 🔖 Save To Your Account