To answer you question "DOES THIS LINE MAKE SENSE?", in your example it does not. That is because the event source and target are both the same. I am going to rewrite your code a bit.
class SOTest1 : Control
{
private bool bar = true;
private bool foo { get; set; }
TextBox textBox;
void Initialize()
{
textBox = new TextBox();
textBox.Click += ClickHandler;
this.Disposed += DisposeControl;
}
void ClickHandler(object sender, EventArgs e)
{
this.foo = bar;
}
void DisposeControl(object sender, EventArgs e)
{
textBox.Click -= ClickHandler;
this.Disposed -= DisposeControl; // DOES THIS LINE MAKE SENSE?
}
}
In this case, since Control
implements IDisposable
which calls the Disposed
event at the end of the disposal, both the object with the event and the event handler are the same object. So, the C# garbage collector is going to see that the object and all references have been disposed and will clean it all up.
Also, since textBox
and its event handlers are contained within that object, the textBox.Click -= ClickHandler
is also redundant, as it will all be cleaned up by the GC when the SOTest1 object is disposed.
It's not a bad practice to clean up event subscribers, but, it does add code that is unnecessary much of the time. C# does a great job of cleaning up resources when your code has finished with them.
There are some cases where memory leaks can happen, like if the lifecycle of the object with the handler is shorter than the lifecycle of the object with the event. The main answer in this article has a good example of that case: What best practices for cleaning up event handler references?