Home All Groups Group Topic Archive Search About

scope and object assignment

Author
28 Apr 2006 4:54 AM
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

Author
28 Apr 2006 5:09 AM
Tom Shelton
James wrote:
Show quoteHide quote
> 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

--
Tom Shelton [MVP]
Author
28 Apr 2006 5:16 AM
James
That's good enough for me.

Thanks Tom.