Let's assume I have a C# class which looks like this:
public class MyClass {
public SomeObject TheObject { get; }
public MyClass() {
TheObject = new SomeObject();
TheObject.MyEvent += MyEventHandler;
}
private void MyEventHandler() {
// some code
}
}
The class creates an internal object called TheObject of type SomeObject, and adds an event handler to an event on this object.
Since TheObject is a public property, that means that any other piece of code can maintain a pointer to this object; And this will, in turn, keep the object of type MyClass alive, because TheObject has a pointer to MyClass in the form of an event handler.
So, I assume the only way to keep this code safe from this event is to add a finalizer to MyClass:
public ~MyClass() {
TheObject?.MyEvent -= MyEventHandler;
}
This is too bad because the finalizer will bump up objects of type MyClass to the next GC generation, but am I correct that this is the only way to avoid this potential memory leak?