We need you!

We're working hard on the next version of Developer Fusion. Let us know what you think we should be up to!

Members

Technology Zones

Articles

Hosted By

MaximumASP

Info

Rated
Read 41,775 times

Contents

Downloads

Related Categories

Windows Form Designer generated code - Controls and IDisposable

palom

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.

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 .NET framework, publisher of the www.VBInfoZine.com ezine and the author of the Dynamic AutoComplete Tool .NET component (dact.lamarvin.com).

Comments