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?
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With