scope and object assignment

  • Thread starter Thread starter James
  • Start date Start date
J

James

Hi.

I just had success doing something that I thought should fail.

Well maybe I did. I'm not sure.

In short, I assigned a locally declared object to a module level object
and the module level object retained the values of the local even after
the local went out of scope.

I was expecting the module level object to have a reference to an
object on the stack, which in my old C programming days would have
killed the program.

Does anyone know why this apparent copying of an object worked?

Public class Aaa
Private m_MyObjects as New MyObjects ' collection of MyObject
Private m_MyObject as MyObject '

'
' lots of code snipped
'

Private Sub Example(ByVal testID As Integer)
For each myObject as MyObject in m_MyObjects
If myObject.TestID = testID Then
m_MyObject = myObject
Exit For
End if
Next
End Sub

End Class
 
James said:
Hi.

I just had success doing something that I thought should fail.

Well maybe I did. I'm not sure.

In short, I assigned a locally declared object to a module level object
and the module level object retained the values of the local even after
the local went out of scope.

I was expecting the module level object to have a reference to an
object on the stack, which in my old C programming days would have
killed the program.

Does anyone know why this apparent copying of an object worked?

Because the object is not created on the stack. The object variable is
on the stack - but the actual object lives on the heap. So, when you
make the assignment you are copying the address of the object, not the
object.

HTH
 
Back
Top