I want to make Windows Forms controls readonly and IDisposable.
Is this is a good thing or a bad thing and what do I have to watch out for when calling Dispose?
I have a Tab (PageTab) that I extend and insert a Panel which has a listview and another Toolbar control into. These tabs then get inserted into a tab control (all native .NET Windows Forms controls).
When the user closes one of these tabs I call the Dispose method (which follows the MSDN way of implementing IDisposable).
Is it wise or suggested to declare the controls as read-only (see below)?
protected readonly ListView _AccountsList = new ListView();
protected readonly Panel _Panel = new Panel();
Because in the Dispose method I just call _Panel.Dipose(), etc. on them, but I cannot set them to null. I want to avoid leaks as much as I can and have things garbage collected.
What’s the best way for a non-Designer GUI development and disposing them?
The default implementation of Control.Dispose (inherited by TabPage) is quite sufficient. It iterates the child controls as stored in the Controls collection member and calls their Dispose() method. You don’t have to help.
There are only two cases where you should call Dispose() explicitly:
The latter case is not in fact a leak, the Control class’ finalizer ensures that the window handle for the dialog eventually is released, assuming there are no live references left to the dialog object.
Control is one of the very few classes where forgetting to call Dispose() can in fact cause an uncontrollable resource leak. You are correct in that you have to call Dispose() explicitly on your TabPage derived object to dispose it when you remove the page. But you don’t have to worry about its child controls.