1

Whenever I am defining my own events, I use a pattern such as the following (which I believe is how the MSDN recommends doing it):

public class MyEventClass
{
    private bool _value; // Backing variable
    public bool Value
    {
        get { return _value; }
        set
        {
            if (value != _value) // Only raise event if value is changed/different
            {
                _value = value;
                OnValueChanged(EventArgs.Empty);
            }
        }
    }

    public event EventHandler ValueChanged; // Anything can subscribe to the event
    protected void OnValueChanged(EventArgs e) // Only this and children can invoke event
    {
        if (ValueChanged != null)
            ValueChanged(this, e);
    }
}

Thus, the client code just needs to subscribe to the event and it automagically works.

However, it feels cumbersome to pass the EventArgs e parameter, in particular with a class that uses EventHandler to raise its events, since the base EventArgs has no data to it, only EventArgs.Empty.

Would it be considered a faux pas to change it to this?

protected void OnValueChanged()
{
    if (ValueChanged != null)
        ValueChanged(this, EventArgs.Empty);
}
  • What is it hurting by being there? Will you have to add it back later when you find a need to pass event arguments? Probably... – Adam Zuckerman May 10 '14 at 2:16
  • 1
    I only thought of it as a convenience to save myself some effort while writing the class. But you're absolutely right in that it could change later (it probably won't, but still...), and it would be a breaking change, so I may as well do it right the first time. Thanks! – Kyle Baran May 10 '14 at 2:36
  • In this particular case, isn't it more normal to use a PropertyChangedEventArgs and -Handler, and pass as the argument the property name? Or is this just a bad example? – Magus May 12 '14 at 14:10
  • My code might be a bad example, but I was pulling my design and naming conventions from a few .NET classes, which use the default EventArgs and -Changed nomenclature. – Kyle Baran May 13 '14 at 2:30
3

Is it wrong? No. Will it cause people to complain about your code? No.

Will it sidetrack some busy developer for a couple of minutes while he tries to find out what the parameters are and whether they will help solve his problem? Could be..

Will it make your class easier to use...?

Standards and patterns are useful because they are easily recognized and used (or ignored). Deviating from conventions should be done for a purpose, not just because you can. This applies whether it is bracket style, parameter names or argument list. Do it for a reason, not just because it compiles.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.