Scope?

  • Thread starter Thread starter Samud
  • Start date Start date
S

Samud

Hi,

I've got a question about something which actually works, but I'd like to
know why...

If you create a form in a subroutine and "show" it, once the subroutine
finishes, technically the new form should be out of scope. I guess in a
sence it is, because you can never "get ahold of it" again. However the
form is still there. Maybe my question should be, is the following code bad
style and could it lead to some undesirable effects?

Private Sub MySub()
Dim f as new SomeForm()
f.show()
End Sub
 
If you create a form in a subroutine and "show" it, once the subroutine
finishes, technically the new form should be out of scope. I guess in a
sence it is, because you can never "get ahold of it" again. However the
form is still there. Maybe my question should be, is the following code bad
style and could it lead to some undesirable effects?

First of all, scope != lifetime in .NET. An object can still be alive
in memory after it goes out of scope, but before the garbage collector
removes it.

For forms specifically, there's some additional magic behind the
scenes to keep the Form objects alive as long as the window is shown.
So no, your code isn't "bad".



Mattias
 
Thanks a lot for the response.

I've got a follow up question:

Suppose I have a 'global' collection called MyCollection. I then fill it in
a subroutine like:

Private Sub FillCollection()
Dim i as integer
for i = 1 to 10
Dim SomeObject as new SomeThingOrOther()
MyCollection.add(SomeObject)
next
end sub

The collection never seems to lose the stuff inside of it, but the
declaration of 'SomeObject' in this scope feels weird.

Is there a chance that the garbage collector could eat the contents of my
collection?

Samud
 
No, it won't -- the MyCollection object is holding a reference to
SomeObject. As long as the object is referenced by something reachable, it
will not be garbage collected. (If you drop your reference to
MyCollection, then it will no longer be reachable -- and neither will
SomeObject. At this point, they're both candidates for garbage collection)


Samud said:
Thanks a lot for the response.

I've got a follow up question:

Suppose I have a 'global' collection called MyCollection. I then fill it in
a subroutine like:

Private Sub FillCollection()
Dim i as integer
for i = 1 to 10
Dim SomeObject as new SomeThingOrOther()
MyCollection.add(SomeObject)
next
end sub

The collection never seems to lose the stuff inside of it, but the
declaration of 'SomeObject' in this scope feels weird.

Is there a chance that the garbage collector could eat the contents of my
collection?

Samud


code
 
Back
Top