Follow up on what type am I ?

Back when I was still at Xojo I wrote a blog post about what type of variable am I ?

This is a follow up on that to maybe help explain things more.

The particular difficulty is arrays. They are simple and can cause deceptive an hard to find bugs BECAUSE they are so easy to use and the Xojo language appears to do what you intend (but I don’t think it is doing the wrong thing).

Its why its important to know the difference between a value type and a reference type.

The set up for this is simple. A new Class in a desktop project cleverly named Class1. That class has one public property, values() as variant.

The rest of the code is in the Window1.Open event in a desktop project.

It’s important that you turn on Preferences > Debugging > Show Object IDS in variable lists.

The rest of the code is simply this 

Dim theClassInstance As New class1

Dim emptyarray() As Variant

theClassInstance.values = emptyArray // <<< THIS LINE IS WHAT CAUSES THE HAVOC !!!!
// Because arrays are "reference types" this line does not copy each value in the 
// array into a new array
// it simply sets "theClassInstance.values" to refer to the same array as 
// "emptyarray" refers to
// so altering one looks like it alters the other

// for this example turn on Preferences > Debugging > Show Object IDS in variable lists

Break
// now look at the object ID of emptyarray and theClassInstance.values
// they _should_ be the same which means they are the same object so 
// changing one will appear to change the other

theClassInstance.values.append ( "123" )
Break
// now look at the object ID of emptyarray and theClassInstance.values
// they _should_ be the same which means they are the same object so 
// changing one will appear to change the other

Redim emptyarray(-1)
Break
// now look at the object ID of emptyarray and theClassInstance.values
// they _should_ be the same which means they are the same object so 
// changing one will appear to change the other

emptyarray.append ( "123" )
Break
// now look at the object ID of emptyarray and theClassInstance.values
// they _should_ be the same which means they are the same object so 
// changing one will appear to change the other

Redim theClassInstance.values(-1)
Break
// now look at the object ID of emptyarray and theClassInstance.values
// they _should_ be the same which means they are the same object so 
// changing one will appear to change the other

If you run this code at each break point you can see that if you check the array that was NOT touched in code you will see it has also changed to mimic the other.

This is because arrays are reference types and the line

        theClassInstance.values = emptyArray 

copies the REFERENCE – not the values in the array 

Be careful with your references out there !