• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 201
  • Last Modified:

Can't understand why this is working

Hi,

Please see the following code, the output number given is shown in the comments, while this is the result I'm wanting - I'm unsure why this is working. See, at POINT1, I don't understand why the next MessageBox shows 5, as that is from the localObject, not the returnedObject. I'd understand this if the CObjectManager.setObject method argument was ByRef, but it is ByVal so by rights,  this should create a copy of the object, meaning that when we retrieve it, it is effectively a different object than localObject. Why is this?

Thanks,
Uni
Public Sub Main()
  
    Dim localObject As New CTest()
    CObjectManager.setObject(localObject)
    MessageBox.Show(localObject.testVariable)       //Returns 0
    localObject.testVariable = 9
    MessageBox.Show(localObject.testVariable)       //Returns 9
 
    Dim returnedObject As CTest
    returnedObject = DirectCast(CObjectManager.getObject(), CTest)
    returnedObject.testVariable = 5
    MessageBox.Show(returnedObject.testVariable)    //Returns 5
    //POINT1
    MessageBox.Show(localObject.testVariable)       //Returns 5
 
End Sub
 
 
 
Public Interface IObject
End Interface
 
 
 
Public Module CObjectManager
 
    Private activeObject As IObject
 
    Public Sub setObject(ByVal aObject As IObject)
        activeObject=aObject
    End Sub
 
    Public Function getObject() As IObject
        getObject=activeObject
    End Function
 
End Module
 
 
 
Public Class CTest
    Implements IObject
    Public testVariable As Integer
End Class

Open in new window

0
Unimatrix_001
Asked:
Unimatrix_001
  • 2
1 Solution
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
You statement is incorrect:

    "I'd understand this if the CObjectManager.setObject method argument was ByRef, but it is ByVal so by rights,  this should create a copy of the object, meaning that when we retrieve it, it is effectively a different object than localObject."

This is a KEY difference between OBJECTS and PRIMITIVES/STRUCTS.  Since you are passing an INSTANCE of an Object, a copy is NOT being made...a REFERENCE is being passed.  ByVal/ByRef for an Object is different than for a primitive/struct.  A reference is always passed for objects...but when passed ByRef it allows you to change the instance that the reference points to.

See: http://msdn.microsoft.com/en-us/library/eek064h4(VS.80).aspx
0
 
Unimatrix_001Author Commented:
Ah, excellent - thank you. :)
0
 
Unimatrix_001Author Commented:
Couldn't have explained it better :)
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now