Windows Form Designer generated code


A couple of days ago, I've got an email from a fellow developer with a rather interesting question concerning the Visual Studio .NET Windows Forms designer. The guy asked about the meaning of the components member generated by the designer and why it is not used in most of the Forms he designed.

The components member is generated as part of the "Windows Forms Designer generated code" region, which is part of every Form created and managed by means of the Visual Studio .NET Windows Forms designer:

#Region " Windows Form Designer generated code "
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
    If disposing Then
    If Not (components Is Nothing) Then
    End If
    End If
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
#End Region

The code and the comments indicate that the components member is used by the Form to hold the list of components in order to be able to dispose the components as part of the Form.Dispose call.

I've checked the designer-generated code in all my .NET Windows Forms projects and I've realized that the components member is actually used only when a component having a specific constructor is placed onto a Form.

You might recall that a component is a class that implements the System.ComponentModel.IComponent interface (either directly or by deriving from a class that already implements the interface, such as System.ComponentModel.Component). If the component exposes a constructor with the specific signaturePublic Sub New(ByVal c As IContainer), then the components Form member is instantiated and passed to the component's constructor:

#Region " Windows Form Designer generated code "
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container
Me.ImageList1 = _
    New System.Windows.Forms.ImageList(Me.components)
#End Region

Within the New(ByVal c As IContainer) constructor, the component adds itself to the container by calling the IContainer.Add method. Within the Form.Dispose method the components.Dispose method is called ensuring that all the resources held by the Form's components are correctly released.

You might also like...


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.


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.

“To iterate is human, to recurse divine” - L. Peter Deutsch