views:

336

answers:

1

Hello

There are multiple threads(a, b, c etc.) about the fact that Clear() ing items in the .NET component containers does not Dispose them(by calling Dispose(true).

Most frequently, IMHO, the Clear-ed components are not used anymore in the application, so it needs explicitly be Disposed after Clearing them from the parent containers.

Maybe is a good idea that collection's Clear method had a bool parameter dispose that when in true also disposes the collection elements before its removing from the list?

+3  A: 

Asking for modifications like this is pointless, the Windows Forms team has been disbanded quite a while ago. It is in maintenance mode, only security issues and OS incompatibilities are considered.

It is otherwise simple enough to create your own method to do this:

  public static class ExtensionMethods {
    public static void Clear(this Control.ControlCollection controls, bool dispose) {
      for (int ix = controls.Count - 1; ix >= 0; --ix) {
        if (dispose) controls[ix].Dispose();
        else controls.RemoveAt(ix);
      }
    }
  }

Now you can write:

  panel1.Controls.Clear(true);
Hans Passant
IIRC, when you `Dispose` a `Control`, it automatically removes the control from the corresponding `ControlCollection`, so you actually don't need the `RemoveAt` (and might end up with an `IndexOutOfRangeException`).
Aaronaught
yeah... at least for .NET 2 this will not work. But the question is a little bit other. Is there a "risk" do calling "Clear" without Dispose?
serhio
Of course, you'll leak the controls. Wasn't that obvious from the other threads?
Hans Passant
@nobugs: yes, now, in other words, you say that, normally, calling `Clear` without `Dispose` has no sense; Microsoft will not change the code, so all we have to do is remember that, use these methods together for .NET < 3.5 and maybe also implement extension methods in .NET >= 3.5
serhio
Erm, I didn't say that. In fact, I don't think Clear() makes a lot of sense in general. WF was optimized to use UserControls and the designer. Container controls already know how to properly dispose their child controls.
Hans Passant
@nobugs: I think `Clear` it's a classic member of any collection(not only the component one), this should be its sense. Container controls "already know how to properly dispose"? What do you mean? As we can see this is not the "Clear" case. Probably they at least can add an "obsolete" attribute on the controls containers "Clear" method.
serhio
Disposing a control automatically disposes any child control in its Controls collection. No help is needed.
Hans Passant
@nobugs: Yes, you are right. BUT, *after* using CLEAR the parent will have *any* control in its controls collection, so all the controls that was `Clear` ed will remain un `Dispose` d, when the parent control is disposed.
serhio