The memory loss that I think you think of when you attach an event handler to an event on an object (call it “A”), and then lose all references to the object (“B”) that the handler belongs to, Garbage collector can still reach object “B” through event “A” of the object and therefore never collects it. See this question for further discussion.
In your case, you are attaching a handler from Form . When the Form closed and you drop all your links to it, there is no way to get the form from the rest of your code so that the GC happily collects it (when it bypassed it). No leakage will occur.
Based on your last comment, the finalizer implementation may not do what you think. This is just a hook that allows you to execute some cleanup code, and you better implement the IDisposable interface. One thing that I usually do in my classes that expose events is setting the null event in the Dispose method. I.e:.
class Foo : IDisposable { public event EventHandler SomethingHappened;
I do not do this in all my classes, but this is a relatively clean way to remove all handlers from an object when it leaves. You can only do this inside the class itself.
In any case, if you intend to work in Form based on the PreviewMouseLeftButtonDown event, you should instead override the OnPreviewMouseLeftButtonDown method. Attaching event handlers to listen to your own class events is usually bad. Instead, do the following:
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e) {
source share