I frequently end up writing SubscribeToEvents()
and UnsubscribeEvents()
functions that are called in my property setters when a property gets a new value. Although the code to do this is quite simple it feels unnecessary to me as it's basicly duplicates the code (code is the same except from +=
and -=
).
I'm trying to create a small utility class that handles this by having a AddSubscription(EventHandler, EventHandler)
function and an UnsubscribeAll()
function that clears all subscriptions registered by AddSubscription
:
public class EventSubscriber
{
private readonly List<KeyValuePair<EventHandler, EventHandler>> _subscriptions = new List<KeyValuePair<EventHandler, EventHandler>>();
public void AddSubscription(EventHandler toSubscribe, EventHandler subscriber)
{
toSubscribe += subscriber;
_subscriptions.Add(new KeyValuePair<EventHandler, EventHandler>(toSubscribe, subscriber));
}
public void UnsubscribeAll()
{
foreach (KeyValuePair<EventHandler, EventHandler> subscription in _subscriptions)
{
EventHandler toSubscribe = subscription.Key;
EventHandler subscriber = subscription.Value;
toSubscribe -= subscriber;
}
_subscriptions.Clear();
}
}
However, I'm not allowed to pass events in to AddSubscription()
:
EventSubscriber subscriber = new eventSubscriber();
subscriber.AddSubscription(_someControl.SomeEvent, OnSomeEvent);
This fails with error
The event '....' can only appear on the left hand side of += or -=
Is there any way I can avoid this, or am I barking up the wrong tree?