Ideally I want a function something like the following (this example doesn't compile):
void AddRemoveEvent<TEvent, TArgs>(TEvent e, EventHandler<TArgs> h, bool add)
where TArgs : System.EventArgs
{
if (add)
{
e += h;
}
else
{
e -= h;
}
}
Then I can write functions:
void AddRemoveEvents(bool add)
{
AddRemoveEvent(aMemberControl.Click, OnClick, add);
}
I then know I can call the function again to remove all handlers. I'm thinking this would be better than writing, keeping and relying on two functions being kept in sync:
void AddEvents(bool add)
{
aMemberControl.Click += OnClick;
}
void RemoveEvents(bool add)
{
aMemberControl.Click -= OnClick;
}
A colleague has written a handy class that does this kind of stuff that uses reflection. It's very useful, but it relies on the name of the event being passed in as a string. I'm looking for a type safe version. Has anybody got any ideas on if it's possible to write this?
Thanks.
I know I shouldn't really have to unwire stuff everywhere because the garbage collector should take care of most cases. But, sometimes a stray event causes a leak, and so I find it safer to just try and remove all events I add rather than trying to mess about with a profiler trying to identify the ones that do cause problems.
I've seen this related question:
How to remove all event handlers from a control