Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding a large number of custom EventArgs?

Tags:

c#

.net

events

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?

like image 944
Brian Ortiz Avatar asked Feb 27 '23 01:02

Brian Ortiz


2 Answers

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.

like image 131
Jon Skeet Avatar answered Mar 08 '23 03:03

Jon Skeet


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;
    }
}
like image 33
Taylor Leese Avatar answered Mar 08 '23 04:03

Taylor Leese