Say I have a class A and it subscribes to n different events ffrom different classes (Say event1 from class B and event2 from class C). At the time of disposing object of Class A, I want to unsubscribe it from all the events it attached to different classes. I want to do it programmatically i.e. I have access to the object of Class A and I want to know which events it has registered from different classes and then unsubscribe them. Is it possible?
Asked
Active
Viewed 34 times
1 Answers
2
No it isn't. Technically your class A
has no reference at all to the class B
and class C
. The reference goes the other way.
You have to keep track of the events in a field in A
and unsubscribe manually when disposing.

Anders Abel
- 67,989
- 17
- 150
- 217
-
Thanks but actually class A subscribe to events conditionally at run time so it is somewhat hard to keep track of the events it registers to. Any good design pattern u recommend or technique to store events registered. – Kumar Nov 15 '13 at 19:12
-
You have to keep track of all the objects that you have subscribed to events on, and for each object what events. You probably need some kind of list containing an object reference and flags for each event. It's messy, but [there is no good way to reference an event](http://stackoverflow.com/questions/4755988/how-to-reference-an-event-in-c-sharp). – Anders Abel Nov 15 '13 at 19:14