I know if an object instance is passed as an argument to a method, this is always done ByRef.
However, I have a simple example showing that specifying ByRef or not, the behaviour change.
I have a class named MyClass
, with only a destructor and a property:
[code]Public Sub Destructor()
break
End Sub
Public Property value as Integer[/code]
now I have a method (let’s say a Window method):
Private Sub TestMethod(c as MyClass)
c = new MyClass
c.value = 2
End Function
finally in whatever place (let’s say the Window.Open event) I have the following code:
[code]dim c as new MyClass
c.value = 1
TestMethod©
if c isa MyClass and c.value = 1 then
break
end if
[/code]
Running the code I’d expect when in TestMethod the object is inited again, the MyClass.Destructor
is called and when it goes back to the calling code, the instance contained in c has value of 2.
But this is not what’s happening.
Instead the c.Destructor
is called when the method ends and back to the calling code, I have back my untouched instance with value = 1. Like if the argument was passed by value.
Now, if I declare the TestMethod
explicitly telling is ByRef with Private Sub TestMethod(byRef c as MyClass)
then everything starts working as expected. But as the LR says all objects are passed byRef by default, so it should not make a difference:
Xojo LR:
All arrays and objects are passed by reference, not copied, so changes to that array or object will be reflected in the calling method. This is no different than assigning an array or object to a second variable or property.
Can anyone explain why is this weird behaviour?