Do I need to call dispose on ToolStripPanel, ToolStrip, and ToolStripItems?
-
29-06-2021 - |
Question
I build a ToolStripPanel
in code where I add a ToolStrip
and subsequently add several ToolStripButton
s and ToolStripSeparator
s. Do I need to manually go through and remove and/or call dispose on each of these? That is, loop through the buttons and separators and call dispose on them, then remove the ToolStrip
from the ToolStripPanel
and the dispose the ToolStrip
and finally remove the ToolStripPanel
from it's parent control and dispose of it?
UPDATE
Reading the documentation of Control.Dispose it appears that calling Dispose
on a parent will dispose of the children. What's not clear to is whether ToolStripItem
s are proper "children" of the ToolStrip
since you don't add them to the ToolStrip.Controls
collection but rather the ToolStrip.Items
collection. When looking at the ToolStrip.Controls documentation it says this property is not relevant to this class.
Same thing with the ToolStripPanel
as you don't call ToolStripPanel.Controls.Add(toolstrip)
but rather ToolStripPanel.Join(toolstrip)
.
Solution
Yes, ToolStripItems are treated as children. ToolStrip.Dispose() iterates the Items collection and disposes the items. The items are not added to the Controls collection because they are not classes that derive from Control. They are "window-less" controls and use their parent to render themselves. Which makes them very cheap.
ToolStripPanel.Join() does in fact add the ToolStrip to the Controls collection (ToolStrip does inherit from Control). It just needs to do one extra thing, it needs to move the strip in the right spot. And has 4 overloads.
So no extra work necessary, disposing the panel is enough to get its toolstrips and their items disposed as well.
OTHER TIPS
If you're adding these compoents in code, you'll have to dispose of them manually or add them (manually) to the components
collection and it will dispose of them for you).
If you add these controls/components with/in the Designer, you don't have to dispose of them manually. They'll be added to a components
collection that will get disposed by the Designer-generated code. That collection disposes of all the children on the form.