views:

137

answers:

1

Is is possible to delegate events from inner object instance to corrent object's event handlers with a syntax like this:

public class MyControl {
   public event EventHandler Finish;

   private Wizard wizard;
   public MyControl( Wizard wizard ) {
      this.wizard = wizard;

      // some other initialization going on here...

      // THIS is what I want to do to chain events
      this.wizard.Finish += Finish;
   } 
}

The motivation for the above structure is that I have many wizard-like UI flows and wanted to separate the Back, Forward & Cancel handling to a single class to respect Open Closed Principle and Single Responsibility Principle in my design.

Adding a method OnFinish and doing the normal checking there is always possible but on case there are lot's of nested events, it's going to end up with lot's of boilerplate code.

+6  A: 

Two options. First:

 public event EventHandler Finish
 {
     add { wizard.Finish += value; }
     remove { wizard.Finish -= value; }
 }

Second, as you mentioned:

 public event EventHandler Finish;

 wizard.Finish += WizardFinished;

 private void WizardFinished(object sender, EventArgs e)
 {
     EventHandler handler = Finish;
     if (handler != null)
     {
         Finish(this, e);
     }
 }

The benefit of the second form is that the source of the event then appears to be the intermediate class, not the wizard - which is reasonable as that's what the handlers have subscribed to.

Jon Skeet
Thanks, the reasoning behind the second option is good enough to implement the system that way. And thanks for the first option also as I didn't realize there was a syntax for overloading add.
plouh