tags:

views:

72

answers:

2

The class library I'm refactoring has a large number of events (over 50) each with its own Delegate, even though many have the same arguments. I starting switching them all over to use EventHandler and custom EventArgs but it is proving to be tedious and time consuming.

Is there an easier way to handle a situation like this, when you have a huge number of events?

+3  A: 

You certainly don't need your own delegate type - you can use EventHandler<TEventArgs> where TEventArgs is your specific EventArgs subclass.

Refactoring a large mess is always time consuming and annoying. If you change to using method group conversions it can make it easier in the future though:

// This...
foo.SomeEvent += new MyCustomEventHandler(SomeMethod);

// becomes this..
foo.SomeEvent += SomeMethod;

Then if the type of SomeEvent changes, you can change SomeMethod and the subscription will just work, without having to be changed again.

Whether you need several different EventArgs subtypes is a different matter - and impossible to say without knowing about your particular situation. If you need to pass a wide variety of pieces of information, it may indeed make sense.

Jon Skeet
Thanks, I guess I just have to take a hard look at all these delegates.
Brian Ortiz
+1  A: 

I use a templatized event args class like below to avoid having to create a large number of custom event args classes.

public class MessageEventArgs<T> : EventArgs
{
    public MessageEventArgs(T message)
    {
        Message = message;
    }

    public T Message
    {
        get;
        private set;
    }
}
Taylor Leese
I was considering that, but it feels like it loses the desired *meaning* of the event arg - because the value is just "message" rather than "UserID", "ErrorCode" or whatever. (It does potentially achieve the goal stated in the question, of course - I'm just not sure whether it's a *good* way of achieving it.) You'd need one generic type for each arity - i.e. `MessageEventArgs<T>`, `MessageEventArgs<T1, T2>` etc... unless you use `MessageEventArgs<Tuple<string,string>>` on .NET 4. At that point the `EventHandler<T>` becomes horrific ;)
Jon Skeet