Windows Form Designer generated code

Controls and IDisposable

After looking at how the Windows Forms designer handles components, I think it might be useful to have a quick look at how Controls are handled with regards to IDisposable.

Every Windows Forms control derives from the System.Windows.Forms.Control base class, which exposes the Controls property:

Public ReadOnly Property Controls() As ControlCollection

The implementation of the Control.Dispose(Boolean) is overridden in such a way that it iterates through the Controls collection calling the Dispose method for each member of the collection. The Windows Forms Designer "knows" this and the code it generates for Control-derived classes always adds controls to the Control.Controls collection that the Form class inherits from the Control class:

#Region " Windows Form Designer generated code "
...
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.TextBox1 = New System.Windows.Forms.TextBox
...
Me.Controls.Add(Me.TextBox1)
End Sub
...
#End Region

This way, when the Form is being disposed, the contained controls are disposed automatically as well.

This leads me to an important recommendation:

If you've been designing a component that allocates UNMANAGED resources, please double check that you:

  1. Implement the specific Public New(IContainer) constructor and add your component instance to the container by calling the IContainer.Add(Me) method in the constructor. (If you create your component using the Visual Studio .NET 'Component Class' template, it generates the specific constructor for you properly.)
  2. Implement the IDisposable design pattern properly meaning that you do release the unmanaged resources and also that you do that exactly once.

You might also like...

Comments

About the author

Palo Mraz

Palo Mraz United States

I live in Slovakia with my wife, two sons (fulltime), one daughter (occasionally) and a dog. I've been doing Microsoft Windows development since 1988; primarily in VB. I'm a big fan of the MS .N...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“An expert is a man who has made all the mistakes that can be made in a very narrow field” - Niels Bohr