Event handling code often involves writing the same useless lines of code, which in most cases is not needed. It’s all relative to the situation, but often I find myself writing something along these lines:

public class Car
{
private readonly Radio _radio;
public event EventHandler<RadioEventArgs> RadioTogglePower;
public Car(Radio radio)
{
// omitting guard clause
_radio = radio;
_radio.TogglePower += OnRadioTogglePower;
}
private void OnRadioTogglePower(object sender, RadioEventArgs e)
{
if (RadioTogglePower != null) RadioTogglePower(sender, e);
}
}
view raw Car.cs hosted with ❤ by GitHub

There are a couple things to note here:

  • We are simply passing the TogglePower event from the Radio object on to some other possible subscriber further down the chain. To do this, we have a seemingly useless method, OnRadioTogglePower that raises another event.
  • We have to check for null every time we want to fire the RadioTogglePower event in the Car class (the null check event pattern is what I usually hear it called).
Yes, these are just minor annoyances. However, as a programmer, I hate to repeat myself. Also known as laziness. That’s a programmer virtue isn’t it? So to combat these two things I usually do the following:
    • Remove the null check pattern when firing an event. How you say? Well, a thread-safe way, which is nice and concise is to use a blank delegate. In this case it will never be null. And when something else is subscribed to the event, things jive in the usual fashion:

public event EventHandler<RadioEventArgs> RadioTogglePower = delegate { };

    • Remove the useless event forwarding method. It serves no purpose, except to pass the event on to somewhere else. Instead, I prefer to use an anonymous method (or in this case, a simple, one-line lambda expression) directly in the event subscription. The caveat is that you cannot unsubscribe from the event using this technique (which is why I said I usually do it this way). If you need to unsubscribe from the event, you’ll have to do it with a method. Keep in mind that events are a major source of memory leaks in .Net in many situations. There ways to combat the memory leaks such as weak events, event aggregators or plain, old proper resource management. Use your favourite search engine to explore further. Anyway, without further ado, here is a lambda expression used to replace a useless event forwarding method:

_radio.TogglePower += (sender, e) => RadioTogglePower(sender, e);

Short and sweet. Unless, of course the very sight of lambda expressions makes you feel ill. I know you’re out there and I can’t help you.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.