When designing an object, is there a best practice for how to allow the
user of the object to tell the object to remove itself from any
delegates / events it has registered with?
For example.. say we have a static settings class, and it has some
OnChange event. The object I am writing will add a method to the
settings OnChange event in its constructor. Obviously, at some point,
the method needs to be removed from the event so the new object can be
garbage collected. Since IDispose is only supposed to be used for
cleaning up unmanaged memory, where should I put the unwire call? [if
this were c++, i would put it in the destructor, but that isn't an
option in C#]
It seems like the only suitable approach is the following. However, I am
curious if there is some standard naming convention for the methods.
{
// in the constructor, listener adds itself to the settings event
Listener listener = new Listener();
...
// use listener
...
listener.Detach();
listener = null;
}
Also, could move the adding of the object to the event from the objects
constructor to some Attach() method the user most call.
Thanks.