I have a class with a method, Register
that subscribes to a number of events on classes that it contains, using the standard aClass.SomeEvent += the_handler
. This class also has an Unregister
method that unsubscribes from these events using -=
. This works just fine but we're finding that if we add a new event to subscribe to that it's very easy to forget to include the unsubscription in Unregister
. This manual method of maintaining event subscriptions is proving to be fragile.
Is there a way to maintain a list of subscriptions that can be iterated over and unsubscribed from dynamically? (And potentially iterate over and re-subscribe when calling Register
after Unregister
).
Some details: The class has a reference to 3 other classes (currently, but not definitively limited to 3), the various events on these classes are all of type EventHandler
or EventHandler<T>
.