5

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

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
jay_t55
  • 11,362
  • 28
  • 103
  • 174

2 Answers2

5

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
  • 122,218
  • 32
  • 205
  • 338
2

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
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • "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 :) – jay_t55 Feb 06 '10 at 16:08
  • 1
    It won't be disposed when the application exits but when the garbage collector runs which is indeterministic. – Darin Dimitrov Feb 06 '10 at 16:11
  • 3
    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. Feb 06 '10 at 16:21
  • Thank you Darin Dimitrov & dh... Will look into that link now :) – jay_t55 Feb 06 '10 at 17:06
  • I think this will cause memory leaks, see [Hans Passant's answer here:](http://stackoverflow.com/a/2014427/4975230) `...the Control class does not behave like any other .NET class. A Control is kept alive by its Handle property. Which stores the native Windows handle. As long as the native window exists, the Control object cannot be destroyed.` It doesn't seem like the GC is capable of disposing `Control` by itself. – jrh Jan 05 '17 at 14:00