Tony
Tony

Reputation: 33

Removing Closed Form from a List in C#

So, i have a question on using a list of forms and when a form closes, to remove itself from the list in C#. I don't think the garbage collector does it automatically, right?

Let's say I have:

List<SomeGraphForm> GraphGroup = new List<SomeGraphForm>();

....

add the forms...

GraphGroup.Add(x);

When x closes, what is the cleanest way to remove it from the list? Is using FormClosed event the best way (but I am not sure how to pass SomeGraphForm item back to the other class(es)).

Upvotes: 0

Views: 183

Answers (2)

Mr Balanikas
Mr Balanikas

Reputation: 1681

Right, the GC cannot collect something that is still referred to. I would go with this basic approach:

  //code to create and add form
  var form = new Form1();
  form.FormClosed +=form_FormClosed;
  _forms.Add(form);
  form.Show();

  //cleanup
  private void form_FormClosed(object sender, FormClosedEventArgs e)
  {
        var closedForm = sender as Form1;
        _forms.Remove(closedForm);
  }

Upvotes: 2

Patrick Hofman
Patrick Hofman

Reputation: 157048

If you have a base class that you use to derive all forms from, you can unregister in the OnClosed method.

protected override void OnClosed(EventArgs e)
{
    // unregister here
}

Upvotes: 0

Related Questions