Scope of form variables...

  • Thread starter Thread starter craig
  • Start date Start date
C

craig

This may sound like a dumb question, but I am hoping someone might comment
on it....

Consider the following method (assuming that Form1 is a class derived from
System.Windows.Forms.Form) :

private void MyMethod()
{
int i = 1;
Form1 myForm = new Form1();

myForm.Show();
}

Both of the variables, i and myForm, are local variables that should go out
of scope when the method is finished executing. But the myForm variable
continues to live on. Is this correct? Why is the scope of form variables
different than the scope of other types?
 
craig said:
This may sound like a dumb question, but I am hoping someone might comment
on it....

Consider the following method (assuming that Form1 is a class derived from
System.Windows.Forms.Form) :

private void MyMethod()
{
int i = 1;
Form1 myForm = new Form1();

myForm.Show();
}

Both of the variables, i and myForm, are local variables that should go out
of scope when the method is finished executing. But the myForm variable
continues to live on. Is this correct? Why is the scope of form variables
different than the scope of other types?

It's not. The variable itself doesn't live on. However, the form
continues to be shown until it's closed etc and there are no other live
references to it. (The UI system will have a reference to it until it's
closed.)
 
I see. So the "myForm" reference goes out of scope, but the system
maintains its own reference to the form, thus keeping it alive?
 
craig said:
I see. So the "myForm" reference goes out of scope, but the system
maintains its own reference to the form, thus keeping it alive?

Yes. Which is what you want, really - you wouldn't want to start
showing the form and then it disappear at the end of the method, would
you?
 
No, that is not what we would want. But it seemed to me that that is
exactly what should happen unless the variable reference was defined with a
glodal scope rather than a local scope. Knowing that this is not what
hapened lead me to wonder why.

I have been searching MSDN and the literature for information on windows
forms lifecycle, including what happens when forms are created and
destroyed, the order of events, etc., but suprisingly, I can't seem to find
very much.

I really appreciate your input. Thanks!
 
Put simply -

i - int is a value type so it lives on the stack, and is cleaned up on exit.
myForm - Form is a reference type so it effectively lives until its not
referenced by anything and is garbage collected (similar to heap allocations
in C++ - but they are automatically deleted for you when no longer needed).

Paul
 
Back
Top