Monday, September 22, 2014

Getting rid of some boiler plate code in event handling

I came across an easy way to get rid of some boiler plate code I am always writing when writing event handlers. Consider this example:

public event EventHandler SomethingHappened;

private void OnSomethingHappened() {
    var handler = SomethingHappened;
    if (handler != null) {
        handler(this, EventArgs.Empty);

In the OnSomethingHappened() method there's a lot of unnecessary boiler plate code to make sure that we don't run into a NullReferenceException.

With a small change to the setup we can do the same with much less coding. Consider another improved example:

public event EventHandler SomethingElseHappaned = delegate { };

private void OnSomethingElseHappened() {
    SomethingElseHappened(this, EventArgs.Empty);

That was easy! I'm gonna do this from now on!

Happy coding!