Suppose I have a C # class that looks like this:
public class MyClass {
public SomeObject TheObject { get; }
public MyClass() {
TheObject = new SomeObject();
TheObject.MyEvent += MyEventHandler;
}
private void MyEventHandler() {
}
}
The class creates an internal object called TheObject of type SomeObject and adds an event handler to this object.
Since TheObject is publicly available, this means that any other piece of code may contain a pointer to this object; And this, in turn, will keep an object of type MyClass alive, because TheObject has a pointer to MyClass as an event handler.
So, I assume that the only way to keep this code safe from this event is to add a finalizer in MyClass:
public ~MyClass() {
TheObject?.MyEvent -= MyEventHandler;
}
This is too bad because the finalizer is replacing objects like MyClass with the next generation of GC, but can I fix this, is this the only way to avoid this potential memory leak?