C# How to remove and cleanup all events
<p>Ideally I want a function something like the following (this example doesn't compile):</p>

<pre><code>    void AddRemoveEvent&lt;TEvent, TArgs&gt;(TEvent e, EventHandler&lt;TArgs&gt; h, bool add)
        where TArgs : System.EventArgs
    {
        if (add)
        {
            e += h;
        }
        else
        {
            e -= h;
        }
    }
</code></pre>

<p>Then I can write functions:</p>

<pre><code>void AddRemoveEvents(bool add)
{
    AddRemoveEvent(aMemberControl.Click, OnClick, add);
}
</code></pre>

<p>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:</p>

<pre><code>void AddEvents(bool add)
{
   aMemberControl.Click += OnClick;
}

void RemoveEvents(bool add)
{
   aMemberControl.Click -= OnClick;
}
</code></pre>

<p>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 <strong>type safe</strong> version. Has anybody got any ideas on if it's possible to write this?</p>

<p>Thanks.</p>

<p>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.</p>

<p>I've seen this related question:<br>
<a href="http://stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-a-control">http://stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-a-control</a></p>
