Disposing an event/handler

G

Guest

I have a application which involves creating instances of a "Form2" class.
Form2 has an event which I handle in Form1. Instances of Form2 have names
like "Matrix_A", "Matrix_B", etc. To create them I use these "populate"
methods:

private void populateA()
{
if (!(Matrix_A == null))
{
Matrix_A.normalclose = false;
Matrix_A.Close();
}
Matrix_A = new Form2();
L1: Matrix_A.TheEvent += new Form2.TheEventHandler(AMethod);
Blah, Blah, other stuff;
}

Later, the instance of Form2 may be closed and perhaps recreated several
times. Do I need to manage (dispose) the event/handler interface created at
L1 above or does it automatically go away when I close the instance?
 
J

Jon Skeet [C# MVP]

mr peanut said:
I have a application which involves creating instances of a "Form2" class.
Form2 has an event which I handle in Form1. Instances of Form2 have names
like "Matrix_A", "Matrix_B", etc. To create them I use these "populate"
methods:

private void populateA()
{
if (!(Matrix_A == null))
{
Matrix_A.normalclose = false;
Matrix_A.Close();
}
Matrix_A = new Form2();
L1: Matrix_A.TheEvent += new Form2.TheEventHandler(AMethod);
Blah, Blah, other stuff;
}

Later, the instance of Form2 may be closed and perhaps recreated several
times. Do I need to manage (dispose) the event/handler interface created at
L1 above or does it automatically go away when I close the instance?

This way round, it's okay. Matrix_A will have a reference to the
instance of Form1, but not the other way round.

If you were closing the instance of Form1 but keeping Matrix_A around
(via anothe reference), you would have been wise to unsubscribe to
avoid Matrix_A keeping the instance of Form1 alive.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top