Wednesday 30 November 2011

Using Actions for Event Handlers

 

I had a thought to day that I would like to be able to build some event handling functionality at run time depending on one thing or another.

Rather than passing a method reference as the handler I wondered if you could pass an Action instead.  My first attempt did not work.

  1. var action = new Action<object, NubmerChangedEventArgs>((sender, eventArgs) =>
  2.     {
  3.         Console.WriteLine(String.Format("The number is now {0}", eventArgs.NewNumber));
  4.     });
  5.  
  6. var eventClass = new NumberTracker();
  7. eventClass.meh += action;

The above results in the following complier error

“Cannot implicitly convert type 'System.Action' to 'ConsoleApplication1.NumberChangedEventHandler'

However you can use the action to create an instance of the Event handler that can be used to handle the event.

  1. var action = new Action<object, NubmerChangedEventArgs>((sender, eventArgs) =>
  2.     {
  3.         Console.WriteLine(String.Format("The number is now {0}", eventArgs.NewNumber));
  4.     });
  5. var handler = new NumberChangedEventHandler(action);
  6.  
  7. var eventClass = new NumberTracker();
  8. eventClass.meh += handler;

In the end I did not require this ability as I ended up re-thinking the structure of my code.  But thought it was quite interesting none the less.

No comments:

Post a Comment