Like the default C# template in Visual Studio, I've defined a Windows Form
as a static object as shown below:
public static FormMain formMain;
static void Main()
{
formMain = new FormMain();
Application.Run(formMain);
formMain.Dispose();
}
As you can see, I've allocated a memory space (using new
) for this static form before calling it and freed the memory (using Dispose
) after the form has been closed.
However, within this static form, I've defined a couple of non-static objects (say, labels), as shown below:
public FormMain()
{
// some code here
Label myLabel1 = new Label();
Label myLabel2 = new Label();
Label myLabel3 = new Label();
// some code here
}
Now, I've two questions:
Do I have to
Dispose
these non-static objects as well or whether they are disposed (memory freed) as soon as theformMain.Dispose();
line is invoked?If I need to dispose these non-static objects, at what stage of the program should I prefer to use
Dispose
(like, in theFormClosed
or in theFormClosing
event)?
Note: I try not to use the form design facility in Visual Studio, but prefer to code the form line by line.