tags:

views:

79

answers:

2

Hi All

Simple question...

I have controls that the user can drag around on my form at runtime. And they can also delete them... Should I just Call .Dispose(); when they click the delete button, or should I do something like panel1.Controls.Clear(Control); ? ...Or something else?

Thanks :)

Bael

+2  A: 

Just remove the control from the panel:

panel.Controls.Remove(someControlInstance);

Once there are no more references to it, it will be subject to garbage collection and unmanaged resources will be properly disposed.

Darin Dimitrov
"Subject to Garbage Coll.."... So, it will be disposed once the application exits? Would it make any difference (performance wise) if I could somehow Dispose of it right after I remove it from the Panel Control? p.s. Thanks for the answer :)
baeltazor
It won't be disposed when the application exits but when the garbage collector runs which is indeterministic.
Darin Dimitrov
It will be disposed when GC decides and that could happen in the middle of your application run as well as in the end. The difference here is that if you call Dispose() explicitly the object finalization will be performed and on next run GC will clean up object's memory otherwise in first run GC will put the object to finalization queue and clean its memory on another run. more on the topic here: http://msdn.microsoft.com/en-us/library/ms973837.aspx
dh
baeltazor
+1  A: 

You should remove it from the parent Controls collection as described in Darin Dimitrov's response, and also call Dispose:

panel.Controls.Remove(someControlInstance);
someControlInstance.Dispose();

You should always call Dispose on objects that implement IDisposable when you have finished with them, so that any unmanaged resources they own are immediately released.

Joe
Just what I was hoping to hear. Thank you very much Joe.
baeltazor