Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing Controls on Winforms

Tags:

c#

winforms

Why does Visual Studio add this code to the Class.Designer.cs partial class. Can anyone tell me when this components variable is going to get some value? What's the pattern to follow here?

private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if(disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
like image 912
jmayor Avatar asked Feb 04 '23 06:02

jmayor


2 Answers

It is code that is produced by the Form item template (common7\ide\itemtemplates\csharp\windows forms\1033\form.zip\form.designer.cs). It actually has a bug, the InitializeComponent() method it contains initializes the "this.components" variable unnecessarily. You can safely delete the statement from the code if your form doesn't have any components. The designer will automatically put it back if you add a component later.

Another thing that is not so nice is that the Dispose() method is put in the Designer.cs file. It really belongs in the form.cs file so you can add Dispose() calls for fields in your form that should be disposed. Don't hesitate to move the code yourself, modifying the designer file this way doesn't have any unpleasant side-effects. Just stay away from the code that's bracketed with the "generated code" region.

As mentioned in most other answers, this code is necessary to call the Dispose() method of any components that you've dropped on the form when the form is closed. Controls on the form need to be disposed as well but that's automatic. The Form class finds them back by iterating the Controls collection.

like image 73
Hans Passant Avatar answered Feb 05 '23 21:02

Hans Passant


The private field components is used to track disposable components on your form. Try dragging in a Timer component, and you should see something like this in the designer generated code:

this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);

The pattern displayed in the Dispose(bool) method is usually referred to as the disposable pattern. Basically, the pattern ensures that all of the tracked components will be disposed, even if you never call the Dispose method explicitly, in which case the base class of your form will call the Dispose method in its finalizer (during garbage collection).

like image 29
Jørn Schou-Rode Avatar answered Feb 05 '23 20:02

Jørn Schou-Rode