Event Horizon

2 12 2012

Not sure how anyone else is writing event raise methods but if they’re like me I’m sure at some point they mostly did:

private void RaiseHitDetected()
  if (HitDetected != null)
    HitDetected(this, new SomeArguments);

Rinse, repeat…
Well, after about five of these I got tired and wrote a little macro that did it for me. It wasn’t the right solution and I hate the Visual Studio’s macro system so back to the drawing board. Wasn’t long before I came up for air and remembered a little thing called extension methods! yay!

public static class Extensions
  public static void Raise(this object caller, EventHandler handler, EventArgs args)
    Assert.IsNotNull(caller, "Unable to call raise on null object");
    if (handler != null)
      handler(caller, args);

And then whenever my objects need to raise events;

public void TakeDamage()
  this.Raise(TookDamage, null);

For the flip-side of it I’ve also attached an extension method for the EventHandler class itself (which looks pretty similar so I won’t write it up) for those cases when we need static events (please don’t need static events…).

And… That’s all about it…

“The butterfly in reverse here is me”