Pages

Monday, October 7, 2013

Event extension

To send notification from one class to an other Event is the best way. But to avoid exceptions we need to check it every time whether it is null or not. It isn't a big deal but a few extra lines every time you want to fire an event, and with every line you write in your code also incrase the possibility of a bug. So, why not an extension method?

public static class EventExtensions
{
   public static void RaiseEvent(this EventHandler handler, object sender, EventArgs e)
   {
      var local = handler;
      if (local != null)
      {
         local(sender, e);
      }
   }
}

Sooo easy. Store handler into a local variable to avoid "Access to modified closure" issue and simply fire an event, if it is not null. In practice it would be something like this:

public class SampleClass
{      
   private event EventHandler CustomEvent;

   public SampleClass()
   {
      this.CustomEvent.RaiseEvent(this, EventArgs.Empty);
   }
}

One simple line instead of five and any changes you might need to make in your application requires to change only one simple extension method. What do I mean? For example log every event.

No comments:

Post a Comment