Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are EventArg classes needed now that we have generics

With generics, is there ever a reason to create specific derived EventArg classes

It seems like now you can simply use them on the fly with a generic implementation.

Should i go thorugh all of my examples and remove my eventArg classes (StringEventArgs, MyFooEventArgs, etc . .)

public class EventArgs<T> : EventArgs
{
    public EventArgs(T value)
    {
        m_value = value;
    }

    private T m_value;

    public T Value
    {
        get { return m_value; }
    }
}
like image 623
leora Avatar asked Nov 22 '08 15:11

leora


1 Answers

What you are describing are essentially tuples, grouped values used for a particular purpose. They are a useful construct in functional programming and support that style very well.

The downside is that their values are not named, and they require context to be understood. EventArgs by their very nature are often consumed far away from their relevant context. Therefore, tuple-esque EventArgs can be very confusing for the consumer.

Let's say we have an event indicating some division has been completed, and it carries the numerator, denominator, and result:

public event EventHandler<EventArgs<double, double, double>> Divided;

The event handler has some ambiguity:

private void OnDivided(object sender, EventArgs<double, double, double> e)
{
    // I have to just "know" this - it is a convention

    var numerator = e.Value1;
    var denominator = e.Value2;
    var result = e.Value3;
}

This would be much clearer with an EventArgs representing the event:

private void OnDivided(object sender, DividedEventArgs e)
{
    var numerator = e.Numerator;
    var denominator = e.Denominator;
    var result = e.Result;
}

Generic reusable EventArgs classes ease development of the mechanism at the expense of expressing intent.

like image 125
Bryan Watts Avatar answered Sep 26 '22 03:09

Bryan Watts