Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to "chain" EventHandlers in c#?

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.

like image 500
plouh Avatar asked Feb 24 '10 07:02

plouh


People also ask

Are event handlers synchronous?

That's correct. All event handlers are fired synchronously and in order of binding.

What is an event handler in C?

C event handlers allow you to interface more easily to external systems, but allowing you to provide the glue logic. The POS includes a small open source C compiler (TCC) which will dynamically compile and link your C code at runtime. Alternatively, you can precompile and ship a DLL/EXE with your functions.

How are event handlers invoked?

Derive EventArgs base class to create custom event data class. Events can be declared static, virtual, sealed, and abstract. An Interface can include the event as a member. Event handlers are invoked synchronously if there are multiple subscribers.


1 Answers

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)
     {
         handler(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.

like image 86
Jon Skeet Avatar answered Oct 03 '22 16:10

Jon Skeet