Lobuno
Lobuno

Reputation: 1405

Dynamically creating and freeing controls in C#

Being a newby in .NET land and coming from a Delphi background, I am accustomed to create controls dynamically and FREE them manually when needed.

In .net, being garbage collected and so, I guess you don't need to explicitly free the controls.

In my case (WinForms), I dynamically populating a flowLayoutPanel with panels, that contains some other controls. In some cases, I need to remove some panels. What I'm doing to achieve that is

flowPanel.Controls.Remove(thePanelToRemove);

This have the needed effect: the panel disappears from the flowLayoutPanel, but what I don't get is: does the garbage collector deletes the control? That would be the desired behavior because I will be creating lots of controls that won't be used anymore when the user deletes them. If not, how can I be sure that the controls get freed? Something like (pseudocode)

flowPanel.Controls.Remove(thePanelToRemove);
thePanelToRemove.Free();

or similar?

Upvotes: 1

Views: 335

Answers (3)

Tim M.
Tim M.

Reputation: 54359

Assuming the control isn't referenced by something else, it's reference count will drop to zero when removed and it will be garbage collected as expected. This is a simplified description (links below if you want to read more) but as a general rule for fully managed resources you rarely need to worry about deterministic disposition and finalization.

Of course, any unmanaged resources referenced by the control should be release and/or disposed of properly. An unmanaged resource could be a file stream, database connection, reference to an unmanaged byte array allocated for image processing, a handle to a Window obtained from the Win32 API, etc.

Overview of garbage collection in .Net (old article but still appears accurate, other than GC changes for c# 4.0).

More garbage collection.

Upvotes: 1

Emond
Emond

Reputation: 50672

Short answer: yes, the garbage collector will remove the control when memory is needed.

Longer answer: Some controls claim resources that can't be freed by the garbage collector. Those controls implement the IDisposable interface and you should call dispose on the control when you no longer need it. The Dispose will clean up these unmanaged resources.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

This have the needed effect: the panel disappears from the flowLayoutPanel, but what I don't get is: does the garbage collector deletes the control?

Yes, when an object falls out of scope it is eligible for garbage collection. You don't need to be calling any .Free method.

Upvotes: 1

Related Questions