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”




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: