Event Handling - Reducing Redundant Code

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);
    }
}


There are a couple things to note here:
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:


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.

Labels: , , ,